#include<assert.h> #include<iostream> using namespace std; const int stackIncreament=20; template<class T> class SeqStack{ public: T *elements;//存放栈中元素的栈数组 int top; int maxSize; SeqStack(int sz=50); ~SeqStack(){ delete[]elements; } void Push(T& x); bool Pop(T& x); bool getTop(T& x); bool IsEmpty(){ return (top==-1)?true:false; } bool IsFull(){ return (top==maxSize-1)?true:false; } int getSize(){ return top+1; } void MakeEmpty(){ top=-1; } friend ostream& operator<<(ostream& os,SeqStack<T>& s){ os<<"top="<<s.top<<endl; for(int i=0;i<=s.top;i++){ os<<i<<":"<<s.elements[i]<<endl; } return os; } }; template<class T> SeqStack<T>::SeqStack(int sz):top(-1),maxSize(sz){ elements=new T[maxSize]; assert(elements!=NULL); } template<class T> void SeqStack<T>::Push(T& x){ if(IsFull()==true){ cout<<"插不进来!"<<endl; return; }else elements[++top]=x; } template<class T> bool SeqStack<T>::Pop(T& x){ if(IsEmpty()==true) return false; x=elements[top--]; return true; } template<class T> bool SeqStack<T>::getTop(T &x){ if(IsEmpty==true) return false; x=elements[top]; return true; } void main(){ SeqStack<char> seq; int num; cout<<"输入插入栈中的数据个数:"; cin>>num; char start=97; for(int i=0;i<num;i++){ seq.Push(start); start++; } cout<<seq; seq.Pop(start); cout<<seq; }
运行截图:
原文链接:https://www.f2er.com/datastructure/383122.html