顺序栈,数组存储栈元素(C++)

来源:互联网 发布:青少年编程培训班 编辑:程序博客网 时间:2024/06/08 04:22

用数组来存储栈中的元素

const int stackIncreament=20;template<class T>class Stack{public:      Stack(int sz=50);      ~Stack(){delete []elements;}      void Push(const T&x);      bool Pop(T&x);      bool getTop(T&x);      bool IsEmpty()const{return (top==-1)?true:false;}      bool IsFull()const{return (top==maxSize-1)?true:false;}      int getSize()const{return top+1;}      void makeEmpty(){top=-1;}      friend ostream& operator<<(ostream& os, Stack<T>& s);private:      T *elements;      int top;      int maxSize;      void overflowProcess();//当数组不够存放数据时,对数组容量进行扩充};template<class T>Stack<T>::Stack(int sz):top(-1),maxSize(sz){      elements=new T[maxSize];      assert(elements!=NULL);}template<class T>void Stack<T>::overflowProcess(){      //私有函数,扩充栈的存储空间      T *newArray = new T[maxSize+stackIncreament];      if(newArray==NULL){cerr<<"存储分配失败!"<<endl;exit(1);}      for(int i=0;i<maxSize;i++)newArray[i]=elements[i];      maxSize=maxSize+stackIncreament;      delete []elements;      elements=newArray;}template<class T>void Stack<T>::Push(const T&x){      if(IsFull())overflowProcess();      elements[++top]=x;}template<class T>bool Stack<T>::Pop(T& x){      if(IsEmpty())return false;      x=elements[top--];      return true;}template<class T>bool Stack<T>::getTop(T& x){      if(IsEmpty())return false;      x=elements[top];      return true;}template<class T>ostream& operator<<(ostream& os, Stack<T> &s){//重载输出      os<<"top="<<s.top<<endl;      for(int i=0;i<s.top;i++)os<<"第"<<i<<"个元素:"<<s.elements[i]<<endl;      return os;}


阅读全文
0 0
原创粉丝点击