栈的链式实现(C++)

上代码:

#ifndef C__CODE_STACK_LINK_H
#define C__CODE_STACK_LINK_H
#include <iostream>
using namespace std;
template<class T>
struct stack_link{
    T data;
    stack_link<T>* link;

    stack_link(){
        link= nullptr;
    }

    stack_link(T x){
        link= nullptr;
        data=x;
    }
};

template<class T>
class Stack{
private:
    stack_link<T>* top;
    stack_link<T>* bottom;

    void rout();
protected:
    void destroy();


public:
    Stack(){
    top=new stack_link<T>;
    bottom=top;
}
    Stack(T x){
    top=new stack_link<T>(x);
    bottom=top;
}
    ~Stack(){
    destroy();
}
    bool push(T x);

    bool pop();

    T Top();


    void out(){
        rout();
    }

    stack_link<T>* getTop();

    bool isempty(){
        return top== nullptr;
    }

};

template<class T>
void Stack<T>::destroy() {
    while(top!=bottom){
        stack_link<T>* current=top;
        top=top->link;
        current->link= nullptr;
        delete current;
    }
    top= nullptr;
    delete top;
    delete bottom;
}

template<class T>
bool Stack<T>::push(T x) {
    if(!top){
        top=new stack_link<T>(x);
        return true;
    }
    else
    {
        stack_link<T>* current=new stack_link<T>(x);
        current->link=top;
        top=current;
        current= nullptr;
        delete current;
        return true;
    }
}

template<class T>
bool Stack<T>::pop() {
    stack_link<T>* current=top;
    top=top->link;
    current= nullptr;
    delete current;
    return true;
}

template<class T>
T Stack<T>::Top() {
    if(top->link!= nullptr)return top->data;
}

template<class T>
stack_link<T> *Stack<T>::getTop() {
    if(!isempty())return top;
    else return nullptr;
}

template<class T>
void Stack<T>::rout() {
    stack_link<T>* ptr=top;
    while (ptr!=bottom){
        cout<<ptr->data<<"->";
        ptr=ptr->link;
    }
    cout<<ptr->data;
    ptr= nullptr;
    delete ptr;
}

#endif //C__CODE_STACK_LINK_H

测试代码:

#include <iostream>
#include "Stack_Link.h"
using namespace std;
int main(){
    Stack<int>s(1);
    for(int i=2;i<20;i++)
        s.push(i);

    cout<<s.Top()<<endl;
    s.pop();
    s.out();

    return 0;
}

结果:
在这里插入图片描述

写在后面:
实现方法基本参照单链表,开始写代码时退出代码是一个无序值,通过调试后找出一些调用方法中定义后没有及时删除的指针,最后代码暂时没发现其它错误。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值