顺序栈实现

 

/* 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;
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值