首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ 堆疊與堆積數據結構實戰:LIFO 原理、陣列實現與 STL 容器適配器

     編輯:C++ 入門

概念釐清:Stack vs 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 前),僅暴露堆疊核心介面。

經典應用場景

  1. 運算式求值/語法分析: 中序轉後序、括號匹配、遞歸下降解析器。
  2. 函數呼叫堆疊模擬: 遞歸轉迭代、協程實現。
  3. 回溯演算法: 迷宮走迷、八皇后、DFS 非遞歸實現。
  4. 編輯器撤銷/重做: 命令模式 + 兩個堆疊。
  5. 瀏覽器前進/後退: 兩個堆疊協作。

效能特徵總結

術語中文資料結構含義記憶體管理含義
Stack堆疊LIFO (後進先出) 抽象資料類型函數呼叫幀、區域變數自動儲存區
Heap堆積優先佇列常用結構 (二元堆)動態記憶體分配區
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
實現PushPopTop空間備註
固定陣列O(1)O(1)O(1)O(N)零分配開銷,容量受限
動態陣列O(1) 攤銷O(1)O(1)O(N)偶爾擴容複製,記憶體連續
鏈表O(1)O(1)O(1)O(N)無擴容,節點分散,快取不友善