平时编程里经常需要用到数据结构,比如 栈和队列 等, 为了避免每次用到都需要重新编写的麻烦现将 C++ 编写的 数据结构 栈 记录下来,以备后用。
将 数据结构 栈 用头文件的形式写成,方便调用。
#ifndef STACK_CLASS #define STACK_CLASS #include<iostream> #include<cstdlib> using namespace std; const int MaxStackSize=50; //栈类的说明 template <class T> class Stack { private: T stacklist[MaxStackSize]; int top; public: Stack(void); void Push(const T &item); T Pop(void); void ClearStack(void); //访问栈顶元素 T Peek(void) const; int StackLength(void) const; int StackEmpty(void) const; int StackFull(void) const; }; //默认构造函数 template <class T> Stack<T>::Stack(void):top(-1) {} template <class T> void Stack<T>::Push(const T &item) { if(top==MaxStackSize-1) { cerr<<"Stack overflow!"<<endl; exit(1); } top++; stacklist[top]=item; } template <class T> T Stack<T>::Pop(void) { T temp; if(top==-1) { cerr<<"Attempt to pop an empty stack"<<endl; exit(1); } temp=stacklist[top]; top--; return temp; } template <class T> T Stack<T>::Peek(void) const { if(top==-1) { cerr<<"Attempt to peek at an empty stack"<<endl; exit(1); } return stacklist[top]; } template <class T> int Stack<T>::StackLength(void) const { return top+1; } template <class T> int Stack<T>::StackEmpty(void) const { return top==-1; } template <class T> int Stack<T>::StackFull(void) const { return top==MaxStackSize-1; } template <class T> void Stack<T>::ClearStack(void) { top=-1; } #endif
具体的调用形式:
运行结果: