棧 是限制插入和刪除只能在一端(棧頂)進行的線性表。遵循 **後進先出 (LIFO)** 原則。
用單鏈表頭插法實現,頭指針即為棧頂。結構:
struct Node {
ElementType element;
Node* next;
};
class Stack {
private:
Node* topPtr;
public:
Stack() : topPtr(nullptr) {}
~Stack() { makeEmpty(); }
bool isEmpty() const { return topPtr == nullptr; }
void push(const ElementType& x) {
Node* newNode = new Node{x, topPtr};
topPtr = newNode;
}
void pop() {
if (isEmpty()) throw UnderflowException();
Node* oldTop = topPtr;
topPtr = topPtr->next;
delete oldTop;
}
const ElementType& top() const {
if (isEmpty()) throw UnderflowException();
return topPtr->element;
}
void makeEmpty() {
while (!isEmpty()) pop();
}
};
棧頂指針指向最新插入節點,`push` 在頭部插入,`pop` 刪除頭部節點,均為 O(1)。
初學者自學數據結構需掌握:
1. C/C++ 指針與動態內存管理
2. 遞歸思維
3. 基本算法分析(時間/空間複雜度)
4. 熟練使用標準庫容器(`std::stack`, `std::vector` 等)驗證思路