主题:求助急:帮忙写个关于栈的入栈和出栈
野百合也有楚天
[专家分:0] 发布于 2008-11-01 20:54:00
要求:将入栈的数字出栈结束后现实栈空 最好有进制的转换
回复列表 (共2个回复)
沙发
elegant87 [专家分:700] 发布于 2008-11-04 19:17:00
#include <iostream>
#include <malloc.h>
#include <cstdlib>
using namespace std;
const int STACKSIZE=50;
const int STACKINCREMENT=50;
template <class T>
class Stack
{
public:
Stack();//初始化一个栈
~Stack();//销毁一个栈
void Push(T e);//入栈
int Pop(T &e);//出栈
bool Empty();//判断是否为空
private:
T *base;//栈底
T *top;//栈顶
int stacksize;//栈的长度
};
template <class T>
Stack<T>::Stack()
{
base=new T(STACKSIZE);
if(!base)
{
cout<<"内存分配失败!"<<endl;
exit(0);
}
top=base;
stacksize=STACKSIZE;
}
template <class T>
Stack<T>::~Stack()
{
int e;
while(!Empty())
{
Pop(e);
delete top;
}
}
template <class T>
void Stack<T>::Push(T e)
{
if(top-base>stacksize)
{
cout<<"栈已经满了,重新分配空间!"<<endl;
base=(T*)realloc(base,(STACKSIZE+STACKINCREMENT)*sizeof(T));
top=base+stacksize;
stacksize+=STACKINCREMENT;
}
*top++=e;
}
template <class T>
int Stack<T>::Pop(T &e)
{
if(Empty())
{
cout<<"栈为空!不能出栈操作!"<<endl;
exit(-1);
}
e=*--top;
return e;
}
template<class T>
bool Stack<T>::Empty()
{
if(top==base) //空栈
return true;
else
return false;
}
int main()
{
Stack<int> s;
int data,m,n,e;
cout<<"请输入一个正整数: ";
cin>>data;
cout<<"\n请输入你要转换的进制: ";
cin>>m;
while(data!=0)
{
n=data%m;
s.Push(n);
data/=m;
}
cout<<"\n转换为"<<m<<"进制的数为: ";
while(!s.Empty())
{
e=s.Pop(e);
cout<<e;
}
cout<<endl<<endl;
system("pause");
return 0;
}
板凳
野百合也有楚天 [专家分:0] 发布于 2008-11-07 13:08:00
进制转换好使就是不执行栈的操作 嘿嘿还是感谢了啊
我自己做了 只是老师一检查它就出错,嗨
我来回复