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;
    }
}

結果:

程序代碼頁面
總結:當棧中的元素個數變化不大時,我們應該使用順序棧(因爲使用鏈棧時多出來的一個指針域也會浪費空間)

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