栈的基本操作(C++)

#include<iostream>
#include<stdlib.h>
using namespace std;
template <class elemtype>
class stack {
    public:
        virtual bool is_empty() const = 0;
        virtual void push(const elemtype &x) = 0;
        virtual elemtype pop() = 0;
        virtual elemtype top() const = 0;
        virtual ~stack() {}
};

template <class elemtype>
class set_stack: public stack <elemtype> {
    private:
        elemtype *elem;
        int top_p;
        int max_size;
        void double_space();
    public:
        set_stack(int init_size = 10) {
            elem = new elemtype [init_size];
            max_size = init_size;
            top_p = -1;
        }
        ~set_stack() { delete[] elem; }
        bool is_empty() const { return top_p == -1; }
        void push(const elemtype &x) {
            if(top_p == max_size - 1) {
                double_space();
            }
            elem[++top_p] = x;
        }
        elemtype pop() {
            return elem[--top_p];
        }
        elemtype top() const {
            return elem[top_p];
        }
};

template <class elemtype>
void set_stack<elemtype>::double_space(){
    elemtype *tmp = elem;
    elem = new elemtype[2*max_size];
    for(int i = 0; i < max_size; ++i) {
        elem[i] = tmp[i];
    }
    max_size *= 2;
    delete[] tmp;
};


int main()
{
    set_stack<int> *s = new set_stack<int>(10);
    cout<<s->is_empty();
   // s->push(3);
   for(int i = 1; i <= 20; i++) {
       s->push(i*10);
   }
   for(int i = 1; i <=20 ; i++) {
      cout << s->top() << endl;
      s->pop();
   }
    cout<<s->top();
    return 0;
}
//这道题目的意义重大,标志我要全面学习C++了!呵呵,加油。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值