C++数据结构——链栈的实现

链栈的实现,其实是针对栈的元素的个数变化量很大的一种情况,使用数组的话有可能造成很大的数组浪费空间,这时使用链栈来动态伸长链栈就变得很优秀了


节点结构

#pragma once
template<typename T>
class Node {
public:
    T data;
    Node<T>  *next;
};

类模板:

#pragma once
#include<iostream>
#include"Node.h"
using namespace std;

template<typename T>
class Stack {
public:
    Stack();
    ~Stack();     
    bool Push(T x);    //元素入栈
    bool pop(T &element);      //栈顶元素出栈
    bool Getpop(T &element) { if (top != NULL) { element = top->data; return true; } return false; } //获取栈顶元素
    bool Empty() { return top == NULL ? true : false; }   //判空
private:
    Node<T> *top;
};


template<typename T>
Stack<T>::Stack() {
    top = NULL;
}
template<typename T>
Stack<T>::~Stack() {
    while (top->next!=NUll) {
        Node<T> *temp = top;
        top = top->next;
        delete temp;
        temp = NUll;
    }
    delete top;
    top = NULL;
}
template<typename T>
bool Stack<T>::pop(T &element) {
    if (top == NULL) {
        cout << "当前栈为空,无法再出栈" << endl;
        return false;
    }
    else {
        Node<T> *temp = top;
        element= temp->data;
        top = top->next;
        delete temp;
        temp = NULL;
        return true;
    }
}
template<typename T>
bool Stack<T>::Push(T x) {
    Node<T> *s = new Node<T>;
    if (s==NULL) {
        return false;    //内存申请失败,返回
    }
    s->data = x;
    s->next = top;
    top = s;
    return true;
}

代码简单测试:

#include<iostream>
#include"Stack.h"
using namespace std;

void popStack(Stack<int> *MyStack);
void getpop(Stack<int> *MyStack);
int main() {
    Stack<int> *MyStack=new Stack<int>;
    int element = 0;
    getpop(MyStack);
    if (MyStack->Empty()) {
        cout << "当前栈空" << endl;
    }
    else {
        cout << "当前栈不为空" << endl;
    }
    /*入栈入五个元素,先入的元素会到栈底,最后入的元素会在栈顶*/
    MyStack->Push(1);         
    MyStack->Push(2);
    MyStack->Push(3);
    MyStack->Push(4);
    MyStack->Push(5);
    popStack(MyStack);
    if (MyStack->Empty()) {
        cout << "当前栈空" << endl;
    }
    else {
        cout << "当前栈不为空" << endl;
    }
    popStack(MyStack);
    popStack(MyStack);
    popStack(MyStack);
    popStack(MyStack);
    getpop(MyStack);
    return 0;
}

void popStack(Stack<int> *MyStack) {
    int element;
    if (MyStack->pop(element))
    {
        cout << "当前出栈元素为:" << element << endl;
    }
    else {
        cout << "当前栈为空,无法再出栈" << endl;
    }
}
void getpop(Stack<int> *MyStack) {
    int element;
    if (MyStack->Getpop(element)) {
        cout << "栈顶元素为:" << element << endl;
    }
    else {
        cout << "当前栈为空,所以无栈顶元素!" << endl;
    }
}

结果:

程序代码页面
总结:当栈中的元素个数变化不大时,我们应该使用顺序栈(因为使用链栈时多出来的一个指针域也会浪费空间)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章