顺序栈的实现 数据结构课本代码 ~~
#include<iostream> using namespace std; const int StackSize=10; template<typename DataType> class SeqStack { public: SeqStack() { int top=-1; } //析构函数-顺序栈的销毁:析构函数为空 ~SeqStack() { } //入栈操作:插入x只需将栈顶元素top加1,然后top的位置填入x void Push(DataType x) { if(top==StackSize-1)//入栈的限制条件:栈满 throw"上溢"; data[++top]=x;//先加1,在调用top } //出栈操作:只需取出栈顶元素,然后将栈顶元素top减1 DataType Pop() { DataType x; if(top==-1)//出栈的限制条件:栈空 throw"下溢"; x=data[top--]; return x; } DataType GetTop() { DataType x; if(top==-1) throw"下溢"; x=data[top]; return x; } int Empty() { if(top==-1) return 1; else return 0; } private: DataType data[StackSize];//存放栈元素的数组 int top;//栈顶元素在数组中的下标 }; //构造函数-顺序栈的初始化:将栈顶指针top置为-1 int main() { int x; SeqStack<int> S{}; cout<<"对15和10执行入栈操作,"; S.Push(15); S.Push(10); cout<<"当前栈顶元素为:"<<S.GetTop()<<endl; try { x=S.Pop(); cout<<"执行一次出栈操作,删除元素"<<x<<endl; }catch(string str){cout<<str<<endl;} try { cout<<"请输入待入栈的元素:"; cin>>x; S.Push(x); }catch(string str){cout<<str<<endl;} if(S.Empty()==1) cout<<"栈为空"<<endl; else cout<<"栈非空"<<endl; return 0; }