数据结构学习——栈的链式描述

学完了栈的数组描述,阿伟要学习栈的链式描述了QAQ

根据分析,用链表的左端作为栈顶更加高效

开发一个类linkedStack

template<class T>
class linkedStack:public stack<T>
{
private:
    chainNode<T>* stackTop;//栈顶指针
    int stackSize;//栈中元素个数
public:
    linkedStack(int initialCapacity=10)
    {
        stackTop=NULL;
        stackSize=0;
    }
    ~linkedStack();//析构函数
    bool empty()const
    {
        return stackSize==0;
    }
    int size()const
    {
        return stackSize;
    }
    T& top()
    {
        if(stackSize==0)
            throw stackEmpty();
        return stackTop->element;
    }
    void pop();
    void push(const T& theElement)
    {
        stackTop=new chainNode<T>(theElement,stackTop);
        //调用chainNode的构造函数,stackTop为next值
        stackSize++;
    }
};

析构函数

template<class T>
linkedStack<T>::~linkedStack()
{
    while(stackTop!=NULL)
    {
        chainNode<T>* nextNode=stackTop->next;
        delete stackTop;
        stackTop=nextNode;
    }
}

pop函数的实现

//删除栈顶节点
template<class T>
void linkedStack<T>::pop()
{
    if(stackSize==0)
        throw stackEmpty();
    chainNode<T>* nextNode=stackTop->next;
    delete stackTop;
    stackTop=nextNode;
    stackSize--;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值