c++实现的一个数组栈
数组栈ArrayStack类源码:
#pragma once //数组栈 template <class T> class ArrayStack { public: //初始化栈 ArrayStack(void) { StackSize = 20; top = -1; elem = new T [StackSize]; } //入栈 void push(T obj) { if(!IsFull()) { top++; elem[top]=obj; } } //出栈 T pop() { if(!IsEmpty()) { return elem[top--]; } } //获取栈顶元素 T GetTop() { if(!IsEmpty()) return elem[top]; } //判断栈是否为空 bool IsEmpty() { if(top == -1) return true; else return false; } //判断栈是否为满 bool IsFull() { if(top == StackSize-1) return true; else return false; } ~ArrayStack(void) { } private: int top; int StackSize; T * elem; };
数组栈测试代码:
//数组栈 ArrayStack<int> *stack = new ArrayStack<int>(); stack->push(2);stack->push(6);stack->push(8);stack->push(4); stack->push(1);stack->push(3);stack->push(5);stack->push(7); while(!stack->IsEmpty()) { std::cout<<stack->pop()<<" "; }