顺序栈

    技术2022-07-10  173

    #include <iostream> #include <algorithm> using namespace std; template <class T> void change_size(T* &a, int oldSize, int newSize) { T* p = new T[newSize]; int size = min(oldSize,newSize); copy(a,a+size,p); delete [] a; a = p; } template <class T> class MyStack { public: MyStack(int defaultCap = 5); ~MyStack() { delete [] stack; } void pop(); //出栈 void push(T & item);//入栈 T & Top(); //获取栈顶元素 bool isEmty(); //判断是否为空 private: int capacity; int top; T *stack; }; template <class T> MyStack<T>::MyStack(int defaultCap):capacity(defaultCap) { top = -1; //栈顶最初的位置设置为-1 stack = new T[capacity]; //申请大小 } template <class T> void MyStack<T>::pop() { if (isEmty()) throw "stack is empty"; stack[top].~T(); top--; } template <class T> bool MyStack<T>::isEmty() { return top == -1; } template <class T > void MyStack<T>::push(T &item) { if (top >= capacity -1) { change_size(stack, capacity, capacity*2); capacity *= 2; } stack[++top] = item; } template<class T> T& MyStack<T>::Top() { if (isEmty()) throw "stack is empty"; return stack[top]; } int main() { MyStack <int> myStack(5); int arry[8] = {1,2,3,4,5,6,7,8}; for (int i = 0; i < sizeof(arry) / sizeof(arry[0]); i++) { myStack.push(arry[i]); cout << myStack.Top() << " " ; } cout << endl; for (int i = 0; i < sizeof(arry) / sizeof(arry[0]); i++) { myStack.pop(); cout << myStack.Top() << " "; } cout << endl; return 0; }

    运行结果:

    Processed: 0.033, SQL: 9