数据结构栈的C++实现

#include <iostream>
#include <stdexcept>
#include <malloc.h>
using namespace std;
namespace my_space
{
    template<class ElemType>
    class stack
    {
    public:
        stack();           //栈的初始化
        ~stack();          //栈的销毁
        void clear();      //清空栈
        bool empty() const;//判断栈是否为空
        int length() const;//返回栈的长度
        ElemType gettop() throw(out_of_range);//返回栈顶元素
        void push(ElemType e); //插入e为新的栈顶元素
        ElemType pop() throw(out_of_range);    //删除栈顶元素
    private:
        class st
        {
        public:
            ElemType *base;
            ElemType *top;
            int stacksize;
            int length;
        };
        st sqstack;
        static const int stack_init_size = 100; //存储空间初始化分配量
        static const int stackincrement = 10;   //存储空间分配增量
    };
    template<class ElemType>
    stack<ElemType>::stack()
    {
        sqstack.base = new ElemType[stack::stack_init_size];
        sqstack.top = sqstack.base;
        sqstack.stacksize = stack::stack_init_size;
        sqstack.length = 0;
    }
    template<class ElemType>
    stack<ElemType>::~stack()
    {
        delete [] sqstack.base;
 sqstack.length = 0;
        sqstack.stacksize = 0;
    }
    template<class ElemType>
    void stack<ElemType>::clear()
    {
        sqstack.top = sqstack.base;
        sqstack.length = 0;
    }
    template<class ElemType>
    bool stack<ElemType>::empty() const
    {
        return sqstack.length == 0;
    }
    template<class ElemType>
    int stack<ElemType>::length() const
    {
        return sqstack.length;
    }
    template<class ElemType>
    ElemType stack<ElemType>::gettop() throw(out_of_range)
    {
        if(sqstack.top == sqstack.base)
            throw("stack is empty!");
        return *(sqstack.top - 1);
    }
    template<class ElemType>
    void stack<ElemType>::push(ElemType e)
    {
        if(sqstack.top - sqstack.base >= sqstack.stacksize)
        {
            sqstack.base = (ElemType*)realloc(sqstack.base, (sqstack.stacksize + stack::stackincrement)*sizeof(ElemType));
            sqstack.top = sqstack.base + sqstack.stacksize;
            sqstack.stacksize += stack::stackincrement;
        }
        *sqstack.top++ = e;
        ++sqstack.length;
    }
    template<class ElemType>
    ElemType stack<ElemType>::pop() throw(out_of_range)
    {
        if(sqstack.base == sqstack.top)
            throw("stack is empty");
        --sqstack.length;
        return *--sqstack.top;
    }
}

int main()
{
    return 0;
}

转载于:https://my.oschina.net/u/196018/blog/383785

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值