基于链表的模板栈

第一次造轮子,使用模板实现的基于链表的栈

简介及代码

首先创建一个结构体模板,即一个链表节点,作为栈的单元。

template <class T>
struct LinkedList{
    T val;
    struct LinkedList<T>* next;
    // LinkedList(T v):val(v),next(NULL){}
};

然后新建一个类,该类有两个成员,分别为栈顶指针top和栈的大小size,top永远指向链表的头部,由于栈只能操作栈顶元素,故新的节点可插入到链表的头部;该类实现了push、pop、empty、getSize四个方法,具体见代码及注释。

//模板链表栈
template <class T>
class Mystack{
public:
    //Initial the stack's size equals 0.
    Mystack(){
        top = NULL;
        size = 0;
    }
    //Use a new node to store data,and make the node's next point to top,then make the pointer top point to the new node.
    void push(const T& node){
        LinkedList<T>* t = new LinkedList<T>;
        t->val = node;
        t->next = top;
        top = t;
        ++size;
    }
    //Make top point to the next node,and return his value.
    T pop(){
        LinkedList<T>* temp = top;
        top = top->next;
        T ret= temp->val;
        delete temp;
        --size;
        return ret;
    }
    //If top is nullptr,the stack is empty.
    bool empty(){
        return top == NULL;
    }
    //Get the stack's size.
    int getSize(){
        return size;
    }
private:
    LinkedList<T>* top;
    int size;
};

测试代码

使用整形和字符串测试正确性以及通用性。

#include <iostream>
#include <string>

int main(){
    Mystack<int> s;
    s.push(1);
    s.push(2);
    s.push(4);
    while(!s.empty()){
        std::cout << "value:" << s.pop() << std::endl;
        std::cout << "size:" << s.getSize() << std::endl;
    }
    Mystack<std::string> str;
    str.push("Zhang si");
    str.push("Li san");
    while(!str.empty()){
        std::cout << str.pop() << std::endl;
    }
    return 0;
}

测试结果

测试结果截图

后记

第一篇博客,水平和语言表达能力有限,勿喷。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值