Stack.hpp
#ifndef MYSTACK_H #define MYSTACK_H template<class T> class Stack { public: Stack(int len = 10) { this->size = len; this->top = -1; stackPtr = new T[len]; } ~Stack() { if (stackPtr != nullptr) { delete[] stackPtr; } } void push(const T& st) { if (isFull()) { cout << "栈已满" << endl; //exit(1); } else { this->stackPtr[++top] = st; } } void pop() { if (this->top == -1) { cout << "空栈" << endl; //exit(1); } else { this->stackPtr[this->top--] = 0; } } int getSize() { return this->top+1; } void print() { for (int i = 0; i < this->top+1; i++) { cout << stackPtr[i] << " "; } cout <<"-----------------------"<< endl; } int isEmpty()const { return top == -1; } int isFull()const { return top == size - 1; } /*T& operator[](int index) { return this->stackPtr[index]; }*/ private: int size; //栈中元素个数 int top;//栈顶位置 T* stackPtr;//保存动态数组指针 }; #endif
Test.cpp
void Test03() { Stack<int> st(8); st.push(1); st.push(3); st.push(5); st.push(7); st.push(9); cout << "stack size: " << st.getSize() << endl; st.print(); st.pop(); cout << "stack size: " << st.getSize() << endl; st.print(); st.push(100); st.push(1000); cout << "stack size: " << st.getSize() << endl; st.print(); st.pop(); st.pop(); st.pop(); st.pop(); st.pop(); st.pop(); st.pop(); cout << "stack size: " << st.getSize() << endl; st.print(); Stack<char> st1(5); st1.push('a'); st1.push('b'); st1.push('c'); st1.push('d'); st1.push('e'); st1.push('f'); cout << "stack size: " << st1.getSize() << endl; st1.print(); }