template <typename T, int MAX_SIZE> class Stack { public:     Stack() :elems(NULL)         , top(0)         , capacity(0)     {}     ~Stack()     {             delete[] elems;             elems = NULL;     }     void Push(const T &elem) //压入元素     {         //int size = sizeof(elems);          checkCapacity();         if (top <= MAX_SIZE)         {             elems[top] = elem;             top++;         }         else         {             printf("栈已满,无法添加数据\n");         }     }     void Pop()           //弹出元素     {         top = top - 1;         if (top == -1)         {             printf("栈已空,没有数据可删除\n");         }     }     T &Top()                //取栈顶     {         return elems[top];     }     const T &Top() const     {         return elems[top];     }     bool Empty() const     {         return top == 0;     }     void checkCapacity()     {         if (top >= capacity)         {             capacity = capacity > 0 ? capacity * 2 : 3;             T* tmp = new T[capacity];             for (int i = 0; i < top; i++)             {                 tmp[i] = elems[i];             }             delete[] elems;             elems = tmp;         }     } private:     T *elems;    //使用数组的方式存储     int top;     int capacity; };
点赞 1

相关推荐

09-15 18:37
已编辑
门头沟学院 后端工程师
让校招回归公平好吗。各大公司学习一下
秋招路在何方:互娱和雷火的笔试是确实是我见过最严格的,支持
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务