通过链表实现栈
#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;
}