顺序栈

来源:互联网 发布:修复老电影软件下载 编辑:程序博客网 时间:2024/06/13 23:38
#include <iostream >using namespace std;const int StackSize=10;template<class T>class SeqStack{public:SeqStack();~SeqStack(){}void push(T x);int  pop();int gettop();int  empty();void print();private:T data[StackSize];int top;};template <class T>SeqStack<T>::SeqStack(){ top=-1;}template <class T>void SeqStack<T>::push(T x){if(top==StackSize-1)throw"上溢";data[++top]=x;}template <class T>int SeqStack<T>::pop(){T x;if(top==-1)throw"下溢";x=data[top--];return x;}template <class T>int SeqStack<T>::gettop(){if(top!=-1) return data[top];}template <class T>int SeqStack<T>::empty(){if(top==-1)return 1;else return 0;}template< class T >  void SeqStack<T>::print()  {      for( int i=0 ; i<=top ; i++)      {  cout<<data[i]<<" ";}      cout<<endl;  }  void main(){ SeqStack<int>s; if(s.empty()) cout<<"栈为空"<<endl; else cout<<"栈非空"<<endl; cout<<"依次将1,2,3入栈"<<endl; s.push(1); s.push(2); s.push(3); s.print(); cout<<"\n"<<endl; cout<<"3元素出栈"<<endl; s.pop(); s.print();}