数据结构之栈(链表栈)

本文介绍了如何使用C++编程实现链表栈的数据结构,详细解析了链表节点定义(chainNode.h)和栈的接口及实现(stack.h)。通过对链表栈的操作,可以进行压栈、弹栈等常见栈操作,为程序设计提供便利。
摘要由CSDN通过智能技术生成


#include"chainNode.h"
#include"exceptions.h"
#include"stack.h"
template<class T>


class linkedStack:public stack<T>
{
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)
    {
        /*chainNode<T>*currentNode = stackTop;
        stackTop = new chainNode<T>();
        stackTop->element = theElement;
        stackTop->next = currentNode; */    //等价于
        stackTop =new chainNode<T>(theElement, stackTop);
        stackSize++;
    }

private:
    chainNode<T> *stackTop; //栈顶指针
    int stackSize;//栈中元素个数

};


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

template<class T>
void linkedStack<T>::pop()
{//删除栈顶元素
    if (stackSize == 0)
    {
        throw stackEmpty();
    }
    chainNode<T> *nextNode = stackTop->next;
    delete stackTop;
    stackTop = nextNode;
    stackSize--;
}

chainNode.h

template <class T>

struct chainNode
{
    T element;
    chainNode<T> *next;

    chainNode<T>(T element, chainNode<T> *next)
    {
        this->element = element;
        this->next = next;
    }
};

stack.h

#ifndef stack_
#define stack_

using namespace std;

template<class T>
class stack
{
public:
    virtual ~stack() {}
    virtual bool empty() const = 0;
    // return true iff stack is empty
    virtual int size() const = 0;
    // return number of elements in stack
    virtual T& top() = 0;
    // return reference to the top element
    virtual void pop() = 0;
    // remove the top element
    virtual void push(const T& theElement) = 0;
    // insert theElement at the top of the stack
};
#endif

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值