1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | #ifndef IOSTREAM #include <iostream> #endif template < class T> class Stack { public : Stack( int MaxSize=10); ~Stack(); bool IsEmpty() const { return top==0;} bool IsFull() const { return top==MaxTop;} T Top() const ; Stack<T>&Add( const T &x); Stack<T>&Delete(T&x); int GetStackSize() const ; //确定堆栈的大小 private : int top; int MaxTop; T *stack; //堆栈元素数组 }; //构造函数 template < class T> Stack<T>::Stack( int MaxSize) { MaxTop=MaxSize-1; stack= new T [MaxSize]; top=-1; //因为top=0的时候等于已经有一个元素了,所以这里为-1 } //析构函数 template < class T> Stack<T>::~Stack() { delete [] stack; } //弹出栈顶 template < class T> T Stack<T>::Top() const { if (IsEmpty()) throw OutOfBounds(); else return stack[top]; } //压入栈 template < class T> Stack<T>&Stack<T>::Add( const T &x) { if (IsFull()) throw NoMem(); top++; stack[top]=x; return * this ; } //弹出栈 template < class T> Stack<T>&Stack<T>::Delete(T&x) { if ((IsEmpty())) throw OutOfBounds(); x=stack[top]; top--; return * this ; } //确定堆栈的大小 template < class T> int Stack<T>::GetStackSize() const { if (IsEmpty()) throw OutOfBounds(); int len=top; return ++len; } |