栈的顺序存储结构称为顺序栈,是利用一组地址连续的存储单元一次存放从栈底至栈顶的数据元素,并用一个变量记录栈顶元素的位置。常用数组存放顺序栈,将栈底放在数组小标较小的那端。
实现代码如下:
#include<iostream> using namespace std; template<class T> class Stack { public: Stack(int); Stack(); ~Stack(); virtual bool IsEmpty(); virtual bool IsFull(); virtual T& GetTop(); virtual bool Push(T&); virtual bool Pop(); virtual void ClearStack(); virtual void Output(); private: int top; //栈顶元素的下标 int MaxSize; //数组的大小 T *stack; //存储栈的数组 }; int main() { Stack <int>stack1(10); //调用构造函数。开数组 for(int i=1;i<=5;i++) stack1.Push(i); //入栈 stack1.Output(); cout<<stack1.GetTop(); return 0; } template<class T> Stack<T>::Stack(int MaxStackSize) { MaxSize = MaxStackSize; stack = new T[MaxSize]; top = -1; } template<class T> Stack<T>::~Stack() { //do nothing } template<class T> bool Stack<T>::IsEmpty() { if(top==-1) return true; else return false; } template<class T> bool Stack<T>::IsFull() { if(top==MaxSize-1) return true; else return false; } template<class T> T& Stack<T>::GetTop() //访问栈顶元素 { return stack[top]; } template<class T> bool Stack<T>::Push(T& x) //入栈 { if(IsFull()) return false; top++; stack[top]=x; return true; } template<class T> bool Stack<T>::Pop() //出栈 { if(IsEmpty()) return false; top--; return true; } template<class T> void Stack<T>::ClearStack() //销毁栈 { top=-1; } template<class T> void Stack<T>::Output() //打印输出 { for(int i=top;i>-1;i--) cout<<stack[i]<<" "; cout<<endl; }
运行结果:
Reference:
《算法分析与设计》
肖南峰 任剑洪 卢雯雯
《Schaum's
Outline of Data Structres with C++》John R.Hubbard