C++ 栈的实现

stack 类实现

点击此处浏览C++官方的stack详细内容

主要功能有以下几个
函数功能
empty测试 stack 是否为空
pop从 stack 的顶部删除元素
push将元素添加到 stack 顶部
size返回 stack 中的元素数量
top返回对 stack 顶部元素的引用

自己实现stack类

只要清楚栈先进后出的原理就很好实现

# include<iostream>
# include<string>
using namespace std;

template<typename T> class Node
{
public:
    T value;
    Node* next = NULL;
};

template<typename T> class Mystack
{
private:
    int length;            //栈的长度
    Node<T>* topNode;      //栈顶结点

public:
    Mystack()
    {
        length = 0;
        topNode = NULL;
    }

    bool empty()
    {
        return length == 0;
    }

    void pop()
    {
        if(empty())           //栈已经为空,不做删除
            return;

        Node<T>* temp = topNode;        //临时结点
        topNode = topNode->next;
        delete(temp);
        length--;
    }

    void push(T val)
    {
        Node<T>* temp = new Node<T>();
        temp->value = val;
        temp->next = topNode;
        topNode = temp;
        length++;
    }

    int size()
    {
        return length;
    }

    T top()
    {
        return topNode->value;
    }

    void clear()
    {
        Node<T>* temp;
        while(length)
        {
            cout<<top()<<endl;
            temp = topNode;
            topNode = topNode->next;
            delete(temp);
            length--;
            
        }
    }

};


int main()                //测试
{
    Mystack<string> s;
    s.push("abc");
    s.push("def");
    s.push("ghi");
    s.push("jkl");
    s.push("mno");
    int len = s.size();
    for(int i = 0; i < len; i++)
    {
        cout<<s.top()<<endl;
        s.pop();
    }
    cout<<s.empty()<<endl;
    return 0;
}

运行结果:
确实是先进后出的

mno
jkl
ghi
def
abc
1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值