顺序栈c++
通过数组建立栈
1 #include <iostream> 2 3 using namespace std; 4 5 template<class T> 6 int ChangeSize1D(T *a, const int oldSize, const int newSize ) 7 { 8 if(newSize<0) throw "new length must be > 0"; 9 T *temp = new T[newSize]; 10 int num = min(oldSize, newSize); 11 copy(a, a+num, temp); 12 delete[] a; 13 a = temp; 14 return 0; 15 } 16 17 template<class T> 18 class MyStack 19 { 20 public: 21 MyStack(int stackcapacity=10); 22 ~MyStack(); 23 24 bool IsEmpty() const; 25 T &Top() const; 26 void Push(const T &item); 27 void Pop(); 28 private: 29 T* Stack; 30 int top; 31 int capacity; 32 }; 33 34 template<class T> 35 inline MyStack<T>::MyStack(int stackcapacity):capacity(stackcapacity) 36 { 37 if(capacity<1) throw "capacity must be > 1"; 38 Stack = new T[capacity]; 39 top = -1; 40 } 41 42 template<class T> 43 MyStack<T>::~MyStack() 44 { 45 delete[] Stack; 46 } 47 48 template<class T> 49 inline bool MyStack<T>::IsEmpty() const 50 { 51 return top == -1; 52 } 53 54 template<class T> 55 inline T& MyStack<T>::Top() const 56 { 57 if(IsEmpty()) throw "stack is empty"; 58 return Stack[top]; 59 } 60 61 template<class T> 62 void MyStack<T>::Push(const T& item) 63 { 64 if(top == capacity-1) 65 { 66 ChangeSize1D(Stack, capacity, 2*capacity); 67 } 68 Stack[++top] = item; 69 } 70 71 template<class T> 72 void MyStack<T>::Pop() 73 { 74 if(IsEmpty()) throw "Stack cannot delete"; 75 Stack[top--].~T(); 76 } 77 78 int main() 79 { 80 MyStack<int> st; 81 st.Push(99); 82 st.Push(22); 83 st.Push(13); 84 85 cout << st.Top() << endl; 86 st.Pop(); 87 cout << st.Top() << endl; 88 st.Pop(); 89 cout << st.Top() << endl; 90 st.Pop(); 91 cout << st.Top() << endl; 92 st.Pop(); 93 cout << st.Top() << endl; 94 cout << "Hello world!" << endl; 95 return 0; 96 }