| 術語 | 中文 | 資料結構含義 | 記憶體管理含義 |
| Stack | 堆疊 | LIFO (後進先出) 抽象資料類型 | 函數呼叫幀、區域變數自動儲存區 |
| Heap | 堆積 | 優先佇列常用結構 (二元堆) | 動態記憶體分配區 |
本文聚焦資料結構 Stack (堆疊)。
堆疊核心操作
- Push (入堆疊/壓入): 在頂端插入元素。
- Pop (出堆疊/彈出): 移除並返回頂端元素。
- Top/Peek (查看頂端): 僅讀取頂端元素不移除。
- Empty/Size: 狀態查詢。
陣列實現固定容量堆疊
#include <iostream>
#include <stdexcept>
template <typename T, size_t MAX_SIZE>
class FixedStack {
T data[MAX_SIZE];
size_t top_idx = 0; // 指向下一個可寫入位置,0 表空
public:
bool empty() const { return top_idx == 0; }
size_t size() const { return top_idx; }
void push(const T& value) {
if (top_idx >= MAX_SIZE) throw std::overflow_error("Stack full");
data[top_idx++] = value;
}
void pop() {
if (empty()) throw std::underflow_error("Stack empty");
--top_idx;
}
T& top() {
if (empty()) throw std::underflow_error("Stack empty");
return data[top_idx - 1];
}
const T& top() const { return const_cast<FixedStack*>(this)->top(); }
};
int main() {
FixedStack<int, 10> st;
for (int i = 0; i < 5; ++i) st.push(i * 10);
while (!st.empty()) { std::cout << st.top() << ' '; st.pop(); }
// 輸出: 40 30 20 10 0 (LIFO)
}
動態陣列實現 (可擴容)
template <typename T>
class DynamicStack {
std::vector<T> data;
public:
void push(const T& v) { data.push_back(v); }
void pop() { if (data.empty()) throw ...; data.pop_back(); }
T& top() { if (data.empty()) throw ...; return data.back(); }
bool empty() const { return data.empty(); }
size_t size() const { return data.size(); }
};
STL 容器適配器:std::stack
#include <stack>
#include <vector>
#include <deque> // 底層預設容器
#include <list>
std::stack<int> s1; // 底層 deque
std::stack<int, std::vector<int>> s2; // 底層 vector
std::stack<int, std::list<int>> s3; // 底層 list
s1.push(1); s1.push(2);
std::cout << s1.top(); // 2
s1.pop();
注意: std::stack 無迭代器、無遍歷、無 clear() (C++11 前),僅暴露堆疊核心介面。
經典應用場景
- 運算式求值/語法分析: 中序轉後序、括號匹配、遞歸下降解析器。
- 函數呼叫堆疊模擬: 遞歸轉迭代、協程實現。
- 回溯演算法: 迷宮走迷、八皇后、DFS 非遞歸實現。
- 編輯器撤銷/重做: 命令模式 + 兩個堆疊。
- 瀏覽器前進/後退: 兩個堆疊協作。
效能特徵總結