顺序栈

//顺序栈的实现
#include <assert.h>
#include <cstring>
template <typename VAL_TYPE>
class Stack
{
private:
    VAL_TYPE* top;
    VAL_TYPE* bottom;
    int size;
    int cap;

    enum { INIT_SIZE=100, INCREMENT_SIZE=10 };
public:
    Stack()
    {
        top=bottom=new VAL_TYPE[INIT_SIZE]; //3+2+1
        size=0;
        cap=INIT_SIZE;
    }
    virtual ~Stack()
    {
        delete bottom;
        top=bottom=NULL;
        size=0;
        cap=0;
    }
    void push(VAL_TYPE& val)
    {
        if(size>=cap)
        {
            VAL_TYPE* p=new VAL_TYPE[cap+INCREMENT_SIZE];
            memcpy(p,bottom,cap);
            delete bottom;

            bottom=p;
            top=bottom+size;
            cap+=INCREMENT_SIZE;
        }


        *top++=val;
        size++;
    }
    void pop()
    {
        assert(size!=0);
        top--;
        size--;
    }
    void get_top(VAL_TYPE& val) const
    {
        assert(size!=0);
        val=*(top-1);
    }

    bool empty() const
    {
        return !size;
    }
    int length() const
    {
        return size;
    }
};

转载于:https://my.oschina.net/HappyTeemo/blog/1558480

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值