#include<iostream>
using namespace std;
template<class T>
class SqStack
{
private:
T *base;
int top;
int stacksize;
public:
SqStack(int m);
~SqStack(){delete[] base;top=-1;stacksize=0;}
void Push(T x);
T Pop();
T GetTop();
int StackEmpty();//测栈空
void ClearStack();//清空栈
void StackTop();//返回栈顶指针
void StackTranverse();//显示栈中元素
};
template<class T>
SqStack<T>::SqStack(int m)
{
base=new T[m];
if(base==NULL)
{
cout<<"栈创建失败,退出!"<<endl;
exit(1);
}
stacksize=m;
top=-1;
}
template<class T>
void SqStack<T>::Push(T x)//入栈
{
if(top==stacksize-1)
throw"栈满,无法入栈!";
top++;
//cout<<top<<endl;
base[top]=x;
}
template<class T>
T SqStack<T>::Pop()//出栈
{
T x;
if(top==-1)throw"栈空,不能出栈!";
x=base[top--];
return x;
}
template<class T>
T SqStack<T>::GetTop()
{
if(top==-1)
throw"栈空,栈顶无元素";
return base[top];
}
template<class T>
void SqStack<T>::StackTranverse()
{
for(int i=0;i<=top;i++)
cout<<"栈中的元素"<<base[i]<<endl;
}
template<class T>
int SqStack<T>::StackEmpty()
{
if(top==-1)
return 1;
else
return 0;
}
template<class T>
void SqStack<T>::ClearStack()
{
if(top==-1)throw"栈空不能清空";
top=-1;
}
void main()
{
SqStack<int> ss(5);
ss.Push(20);
ss.Push(30);
ss.Push(40);
cout<<"出栈的元素为"<<ss.Pop()<<endl;
cout<<"获取栈顶元素为"<<ss.GetTop()<<endl;
ss.StackTranverse();
}
using namespace std;
template<class T>
class SqStack
{
private:
T *base;
int top;
int stacksize;
public:
SqStack(int m);
~SqStack(){delete[] base;top=-1;stacksize=0;}
void Push(T x);
T Pop();
T GetTop();
int StackEmpty();//测栈空
void ClearStack();//清空栈
void StackTop();//返回栈顶指针
void StackTranverse();//显示栈中元素
};
template<class T>
SqStack<T>::SqStack(int m)
{
base=new T[m];
if(base==NULL)
{
cout<<"栈创建失败,退出!"<<endl;
exit(1);
}
stacksize=m;
top=-1;
}
template<class T>
void SqStack<T>::Push(T x)//入栈
{
if(top==stacksize-1)
throw"栈满,无法入栈!";
top++;
//cout<<top<<endl;
base[top]=x;
}
template<class T>
T SqStack<T>::Pop()//出栈
{
T x;
if(top==-1)throw"栈空,不能出栈!";
x=base[top--];
return x;
}
template<class T>
T SqStack<T>::GetTop()
{
if(top==-1)
throw"栈空,栈顶无元素";
return base[top];
}
template<class T>
void SqStack<T>::StackTranverse()
{
for(int i=0;i<=top;i++)
cout<<"栈中的元素"<<base[i]<<endl;
}
template<class T>
int SqStack<T>::StackEmpty()
{
if(top==-1)
return 1;
else
return 0;
}
template<class T>
void SqStack<T>::ClearStack()
{
if(top==-1)throw"栈空不能清空";
top=-1;
}
void main()
{
SqStack<int> ss(5);
ss.Push(20);
ss.Push(30);
ss.Push(40);
cout<<"出栈的元素为"<<ss.Pop()<<endl;
cout<<"获取栈顶元素为"<<ss.GetTop()<<endl;
ss.StackTranverse();
}