链式栈

链式栈不带有头结点,top指针直接指向栈顶。

LinkStack.h

#include<iostream>

using namespace std;

template<class T>
struct LinkNode{
    T data;
    LinkNode<T> *link;
    LinkNode(LinkNode<T>* pre = NULL){ link = pre; }
    LinkNode(T& x, LinkNode<T> *pre = NULL){ data = x; link = pre; }
};

template<class T>
class LinkStack{
protected:
    LinkNode<T> *top;

public:
    LinkStack(){ top = NULL; }
    ~LinkStack(){ makeEmpty(); };
    void makeEmpty();
    bool isEmpty(){ return top == NULL ? true : false; }
    bool push(T &x);
    bool pop(T &x);
    bool getTop(T &x);
    int getSize();
    void output();
};

template<class T>
void LinkStack<T>::makeEmpty(){
    LinkNode<T> *p = top;
    while (top != NULL){
        p = top;
        top = top->link;
        delete p;
    }
}

template<class T>
bool LinkStack<T>::push(T &x){
    LinkNode<T> *p = new LinkNode<T>(x);
    if(p == NULL){
        cout << "内存分配错误!" << endl; exit(1);
    }
    p->link = top;
    top = p;
    return true;
}

template<class T>
bool LinkStack<T>::pop(T &x){
    if (isEmpty() == true) return false;
    LinkNode<T> *del = top;
    x = del->data;
    top = top->link;
    delete del;
    return true;
}

template<class T>
bool LinkStack<T>::getTop(T &x){
    if (isEmpty() == true) return false;
    x = top->data;
    return true;
}

template<class T>
int LinkStack<T>::getSize(){
    if (isEmpty() == true) return 0;
    int cnt = 0;
    LinkNode<T> *p = top;
    while (p != NULL){
        cnt++;
        p = p->link;
    }
    return cnt;
}

template<class T>
void LinkStack<T>::output(){
    cout << "top:   ";
    LinkNode<T> *p = top;
    while (p != NULL){
        cout << p->data << "   ";
        p = p->link;
    }
    cout << endl;
}

Test.cpp

#include"LinkStack.h"
#include<string>

using namespace std;

void main(){

    LinkStack<string> intStack;
    string str1 = "abcd", str2 = "efghji", str3 = "hello,world";
    string str4, str5;

    intStack.push(str1);

    intStack.push(str2);
    intStack.push(str3);

    intStack.output();
    cout << intStack.getSize() << endl;
    intStack.getTop(str4);
    cout << str4 << endl;


    intStack.pop(str5);
    intStack.output();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值