通过链表实现栈

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
#include<iostream>
#include "chainList.cpp"

using namespace std;

template<class T>
class linkedStack {
public:
    explicit linkedStack(int initialCapacity = 10) {
        stackTop = nullptr;
        stackSize = 0;
    }

    ~linkedStack();

    [[maybe_unused]] [[nodiscard]] bool empty() const { return stackSize == 0; }

    [[maybe_unused]] [[nodiscard]] int size() const { return stackSize; }

    int illegalPatameterValue(const string &s) {
        cout << s << endl;
        return -1;
    }

    [[maybe_unused]] T &top() {
        if (stackSize == 0)
            throw illegalPatameterValue("Stack is empty ");
        return stackTop->element;
    }

    void pop();

    void push(const T &theElement) {
        stackTop = new chainNode<T>(theElement, stackTop);
        stackSize++;
    }

private:
    chainNode<T> *stackTop;  // 栈顶指针
    int stackSize; // 栈容量
public:
    chainNode<T> *getStackTop() const;

    [[nodiscard]] int getStackSize() const;

};

template<class T>
linkedStack<T>::~linkedStack<T>() {
    // 构析函数
    while (stackTop != nullptr) {
		// 删除栈顶节点
        chainNode<T> *nextNode = stackTop->next;
        delete stackTop;
        stackTop = nextNode;
    }
}

template<class T>
void linkedStack<T>::pop() {
    if (stackSize == 0)
        throw illegalPatameterValue("Stack is empty");
    // 删除栈顶节点
    chainNode<T> *nextNode = stackTop->next;
    delete stackTop;
    stackTop = nextNode;
    --stackSize;
}

template<class T>
chainNode<T> *linkedStack<T>::getStackTop() const {
    return stackTop;
}

template<class T>
int linkedStack<T>::getStackSize() const {
    return stackSize;
}

// 重载输出
template<class T>
ostream &operator<<(ostream &out, const linkedStack<T> &list) {
    auto stack = list.getStackTop();
    auto size = list.getStackSize();
    for (int i = 0; i < size; ++i) {
        out << stack->element << '\t';
        stack = stack->next;
    }
    return out;
}

int main() {
    auto *stack = new linkedStack<int>(20);
    stack->push(20);
    stack->push(22);
    cout << *stack << endl;
    stack->pop();
    cout << *stack << endl;
    return 0;

}