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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
#ifndef Stack_hpp #define Stack_hpp
#include <iostream> using namespace std;
template <typename T> class Stack { T *data; int top; int size;
public: Stack(); ~Stack();
bool is_empty(); bool is_full(); void push(const T &elem); void pop(); T get_top(); };
template <typename T> Stack<T>::Stack() : top(-1), size(10) { data = new T[size]; }
template <typename T> Stack<T>::~Stack() { delete [] data; data = nullptr; }
template <typename T> bool Stack<T>::is_empty() { if (top == -1) { return true; } else { return false; } }
template <typename T> bool Stack<T>::is_full() { if (top == size-1) { return true; } else { return false; } }
template <typename T> void Stack<T>::push(const T &elem) { if (is_full()) { throw out_of_range("Stack<>::push(): 栈满"); } else { data[++top] = elem; } }
template <typename T> void Stack<T>::pop() { if (is_empty()) { throw out_of_range("Stack<>::pop(): 栈空"); } else { top--; } }
template <typename T> T Stack<T>::get_top() { if (is_empty()) { throw out_of_range("Stack<>::top(): 栈空"); } else { return data[top]; } }
#endif
|