顺序栈实现

来源:互联网 发布:视频交友软件聊天 编辑:程序博客网 时间:2024/06/05 15:49
 

/* stack.h
 **顺序栈实现

 */
 #include<iostream>
 using namespace std;
 #define REALLOCSIZE 10                    /*重新分配内存大小*/
 template<class type>
class stack{
 public:
     stack();
     ~stack(void){free(_arr);}
     void push(const type& item);          /*入栈操作*/
     type pop(void);                       /*出栈操作,返回弹出值*/
     type top(void);                       /*返回栈顶元素*/
     bool empty()const;                    /*判断栈是否为空*/
     void clear(void);                     /*清空栈操作*/
 private:
     type* _arr;                           /*栈内存空间*/
     int _top;                             /*栈顶指针*/
     int _currentsize;                     /*当前栈内存大小*/
 };
 
 /****************具体实现**********************/
 
 template<class type>
 stack<type>::stack(){
     _top=-1;
     _currentsize=REALLOCSIZE;
     _arr=(type*)malloc(REALLOCSIZE*sizeof(type));
 }
 
 template<class type>
 void stack<type>::push(const type& item){
     if(this->_top+1<this->_currentsize){
         _arr[++_top]=item;
     }
     else{
         this->_currentsize+=REALLOCSIZE;
         _arr=(type*)realloc(_arr,this->_currentsize*sizeof(type));
         _arr[++_top]=item;
     }
 }
 
 template<class type>
 type stack<type>::pop(){
     if(this->_top>-1){
         return _arr[this->_top--];
     }
     else{
         cerr<<"ERR!";
         exit(1);
     }
 }
 
 template<class type>
 type stack<type>::top(){
     if(this->_top>-1){
         return _arr[this->_top];
     }
     else{
         cerr<<"ERR!";
         exit(1);
     }
 }
 
 template<class type>
 bool stack<type>::empty()const{
     return this->_top==-1;
 }
 
 template<class type>
 void stack<type>::clear(){
     this->_currentsize=REALLOCSIZE;
     this->_arr=(type*)realloc(_arr,REALLOCSIZE*sizeof(type));
     this->_top=-1;
 }