PDA

View Full Version : Sửa bài stack mở rộng trong lập trình hướng đối tượng



benben
28-04-2009, 22:05
#include<iostream.h>
typedef int Item;
class Stack
{
Item *st,*top;
int size;
void Init(int sz);
void CleanUp();
bool Copy(Stack &t);
public:
Stack(int sz=20)
{
Init(sz);
}
~Stack()
{
CleanUp();
}
Stack(Stack &t)
{
Init(t.size);
Copy(t);
}
bool Full() const;
bool Empty() const;
bool Push(Item x);
bool Pop(Item *x);
Stack &operator<<(Item x)
{
Push(x);
return *this;
}
Stack &operator>>(Item &x)
{
Pop(&x);
return *this;
}
};

void Stack::Init(int sz)
{
st=top=new Item[size=sz];
}

void Stack::CleanUp()
{
if(st)
delete []st;
}

bool Stack::Full() const
{
return (top-st>=size);
}

bool Stack::Empty() const
{
return (top<=st);
}

bool Stack::Push(Item x)
{
if(Full())
{
Stack StackTG(*this);
CleanUp();
Init(2*this->size);
if(!Copy(StackTG))
return false;
else
cout<<"Stack now is double to"<<size<<"\n";
}
*top++=x;
return true;
}

bool Stack::Pop(Item *x)
{
if(Empty())
return false;
*top--;
*x=*top;
return true;
}

bool Stack::Copy(Stack &t)
{
if(size<t.size)
return false;
for(int i=0;i<size;i++)
Push(*(t.st+i));
top=st+size;
return true;
}

void main()
{
static char hTab[]="0123456789ABCDEF";//{'0','1','2','3','4','5','6','7','8','9','A','B',' C','D','E','F'};
Stack S(8); //Stack S;
int n,x;
cout<<"Nhap n ";
cin>>n;
do
{
S.Push(n%16);
n/=16;
}while(n);
cout<<"Doi sang he 16 la: ";
while(S.Pop(&x))
cout<<hTab[x];
cout<<"\n";
}
bài này mình làm để mở rộng stack đó là khi nhập vào một số lớn bất kì thì khi tràn stack tự nhân đôi mà sao lúc chạy ko dúng,ai có thể thì giúp mình nha.
thank...............