顺序栈
#include<iostream> #include<exception> using namespace std; class BadSize: public exception { public: const char* what()const throw() { return "BAD SIZE!"; } }; class OutOfRange: public exception { public: const char* what()const throw() { return "OUT OF RANGE!"; } }; template<class T> class Stack { private: T* stack; int top; int maxSize; void resize(); public: Stack(int initSize = 100); ~Stack() { delete[] stack; } bool isEmpty()const { return top == -1; } int size()const { return top + 1; } void clear()const { top = -1; } void push(const T& value); void pop(); T getTop()const; }; template<class T> Stack<T>::Stack(int initSize) { if (initSize < 0) throw BadSize(); maxSize = initSize; stack = new T[maxSize]; top = -1; } template<class T> void Stack<T>::push(const T& value) { if (top + 1 == maxSize) resize(); stack[++top] = value; } template<class T> void Stack<T>::pop() { if (isEmpty()) throw OutOfRange(); --top; } template<class T> T Stack<T>::getTop()const { if (isEmpty()) throw BadSize(); return stack[top]; } template<class T> void Stack<T>::resize() { T* auxStack = new T[maxSize * 2]; for (int i = 0; i < maxSize; ++i) { auxStack[i] = stack[i]; } maxSize *= 2; delete[] stack; stack = auxStack; } // test int main() { Stack<int> test(3); for (int i = 0; i < 5; ++i) { test.push(i); } for (int i = 0; i < 6; ++i) { test.pop(); cout << test.getTop() << endl; } }