Skip to content

資料結構

前言

程式 = 資料結構 + 演算法。 前面我們學了 CPU 如何執行指令、作業系統如何管理資源。但程式要處理的核心物件是資料——使用者資訊、商品列表、社交關係……這些資料怎麼在記憶體裡組織,直接決定了程式的快慢。

這篇文章會帶你學什麼?

學完這章後,你將獲得:

  • 直覺判斷力:看到一個需求,腦子裡自動浮現該用什麼資料結構
  • 效能分析視角:能判斷效能瓶頸是資料結構選錯了,還是演算法效率低
  • 權衡思維:理解「空間換時間」與「時間換空間」
  • 程式碼閱讀能力:看到 HashMap、Stack、Queue 這些詞不再陌生
章节內容核心概念
第 1 章全景圖四大類資料結構
第 2 章線性結構陣列、鏈結串列、堆疊、佇列
第 3 章雜湊表雜湊函式、衝突處理、O(1) 搜尋
第 4 章樹形結構二元樹、檔案系統樹、DOM 樹
第 5 章圖結構有向圖、無向圖、遍歷演算法
第 6 章效能對比時間複雜度、空間複雜度
第 7 章選型指南場景分析、決策流程

1. 全景圖:資料結構是什麼?

想象你要整理一堆書:

  • 堆在地上:找書要一本本翻——這就是最原始的儲存
  • 按編號放書架:直接去對應位置拿——這就是陣列
  • 按類別分櫃子:先確定櫃子再找書——這就是雜湊表
  • 按書名排序放多層架:每次排除一半——這就是
Data Structure OverviewChoose a data organization model for each scenario
Data structures are like ways to organize a room: clothes in a wardrobe, books on shelves, and small items in drawers.
📚
Linear structures
Data arranged in order, like a row of books
ArrayLinked listStackQueue
🗂️
Hash structures
Fast lookup through a key
Hash tableDictionarySet
🌳
Tree structures
Hierarchy, like a family tree
Binary treeB-treeHeap
🕸️
Graph structures
Complex relationship networks
Directed graphUndirected graphNetwork graph
📚Linear structures
Features
One-to-one relationship between elements
A clear before-and-after order
Can use contiguous storage or linked storage
Use Cases
📝
Arrays: list data
Store ordered data such as student scores or product prices
🔄
Stacks: undo operations
Text editor undo history, last in first out
🎫
Queues: task scheduling
Print queues and task queues, first in first out
Operation Complexity
OperationAverage time
Access elementO(1)
Insert/deleteO(n)
Everyday Analogy
Like train cars connected in order
To find car 5, count directly to it; to insert a new car, you need to break and reconnect links.

所有資料結構可以歸為四大類:

類型資料關係典型代表生活類比
線性結構一對一,排成一排陣列、鏈結串列、堆疊、佇列火車車廂、排隊隊伍
雜湊結構鍵→值對應雜湊表、字典、集合圖書館索引卡片
樹形結構一對多,層級關係二元樹、B樹、堆積家族族譜、資料夾
圖結構多對多,網狀關係有向圖、無向圖捷運路線圖、社交網路

2. 線性結構:最基礎的組織方式

Four Forms of Linear StructuresHow arrays, linked lists, stacks, and queues differ
ArrayContiguous memory, indexed access
0
10
1
25
2
33
3
47
4
59
5
62
✓ Contiguous memory | ✓ Fast access (O(1)) | ✗ Slow insert/delete (O(n))
Operation Comparison
Data structureAccessInsertDeleteFeature
📊 ArrayO(1) fastO(n) slowO(n) slowFixed size
🔗 Linked listO(n) slowO(1) fastO(1) fastVariable size
🥞 StackO(n)O(1) fastO(1) fastOne-end operations
🚶 QueueO(n)O(1) fastO(1) fastTwo-end operations
Real-World Uses
📋
List data
Student scores or product price lists
🖼️
Image processing
Pixel matrix storage
📈
Charts
Data ordered by time

2.1 陣列 vs 鏈結串列

對比維度陣列鏈結串列
記憶體佈局連續的一整塊散落各處,用指標串起來
存取第 n 個直接算地址,O(1)從頭一個個找,O(n)
中間插入後面的都要挪,O(n)改兩個指標就行,O(1)
大小建立時就固定了隨時可以增長

2.2 堆疊和佇列

結構規則操作類比
堆疊後進先出 (LIFO)push / pop一疊盤子
佇列先進先出 (FIFO)enqueue / dequeue排隊買票

3. 雜湊表:最快的搜尋

Hash Tables: Super-Fast LookupFind data directly through a key
📚
A hash table is like a library index card: instead of searching shelf by shelf, you use the index to find the book location directly.
Store data
Hashing process
Input key
apple
Hash function
hash(key) % 10
Array index
0
Hash table
0
apple: apple
1
Empty
2
Empty
3
Empty
4
Empty
5
Empty
6
orange: orange
7
Empty
8
Empty
9
banana: banana
Performance Comparison
Hash table lookup
O(1)
Found instantly
Array lookup
O(n)
Requires traversal
Binary search
O(log n)
Requires sorted data
Common Uses
👤
User table (user ID → profile)
🛒
Shopping cart (product ID → quantity)
📝
Cache system (URL → page content)
🔍
Dictionary (word → definition)

3.1 雜湊表的核心思想

  1. 你給一個(比如 "apple")
  2. 雜湊函式把鍵算成一個數字
  3. 直接到陣列的對應位置找——不用遍歷,一步到位

3.2 雜湊衝突

兩個不同的鍵可能算出同一個索引——這叫雜湊衝突

3.3 雜湊表的效能

操作平均情況最壞情況
搜尋O(1)O(n)
插入O(1)O(n)
刪除O(1)O(n)

雜湊表在你的程式碼裡無處不在

  • JavaScript 的 {} 物件和 Map → 雜湊表
  • Python 的 dict → 雜湊表
  • Java 的 HashMap → 雜湊表

4. 樹形結構:層級關係的表達

Tree Structures: Representing HierarchiesAn organization model like a family tree
Choose a tree type:
50307020406080
Tree Structure Features
🌲
Hierarchy
Nodes have one-to-many parent-child relationships
🎯
Single root node
Except for the root, each node has exactly one parent
🔍
Efficient lookup
Binary search tree lookup is O(log n)
🔄
Multiple traversals
Preorder, inorder, postorder, and level-order traversal
Use Cases
📁
File systems
Hierarchical organization of folders and files
🌐
HTML DOM
Nested structure of web page elements
🏢
Organization charts
Company management hierarchy
🌲
Decision trees
Classification algorithms in machine learning

4.1 二元搜尋樹:有序的樹

一個簡單但強大的規則:左小右大

4.2 平衡樹:防止退化

類型平衡策略典型應用
AVL 樹嚴格平衡需要頻繁搜尋的場景
紅黑樹近似平衡Java TreeMap、Linux 核心
B 樹多路平衡資料庫索引

樹在你的程式碼裡在哪?

  • 檔案系統:資料夾巢狀就是樹結構
  • HTML DOM:就是一棵樹
  • 資料庫索引:B+ 樹讓百萬級資料的搜尋只需要 3-4 次磁碟讀取
  • JSON/XML:巢狀的資料格式本質上就是樹

5. 圖結構:複雜關係的網路

Graph Structures: Representing Complex RelationshipsA network of nodes and edges
ABCDE
Graph properties
Vertices (V)
5
Edges (E)
6
Degree
2.4
Use Cases
🗺️Map navigation (shortest path)
👥Social networks (friend relationships)
🌐Web links (PageRank)
🔗Dependencies (package management)

5.1 圖的三種形態

類型特點類比典型應用
無向圖邊沒有方向微信好友(互相的)社交網路
有向圖邊有方向微博關注(單向的)網頁連結
帶權圖邊有權重城市間的公路(有里程數)地圖導航

5.2 圖的遍歷

遍歷方式策略類比
BFS(廣度優先)先訪問所有鄰居水波紋擴散
DFS(深度優先)一條路走到底走迷宮

6. 效能對比:一張表看清所有資料結構

Data Structures: Containers for DataChoose different storage models for different scenarios
ArrayContiguous memory and fast indexed access
010
120
230
340
450
560
670
780
Access arr[2] = O(1), insert/delete = O(n)
Time Complexity Comparison
OperationArrayLinked listHash tableTree
AccessO(1)O(n)O(1)O(log n)
SearchO(n)O(n)O(1)O(log n)
InsertO(n)O(1)O(1)O(log n)
DeleteO(n)O(1)O(1)O(log n)
Core idea:Data structures are containers for data. Different containers have different tradeoffs. Choosing the right data structure can improve program efficiency by orders of magnitude.
資料結構存取搜尋插入刪除空間
陣列O(1)O(n)O(n)O(n)O(n)
鏈結串列O(n)O(n)O(1)O(1)O(n)
堆疊/佇列O(n)O(n)O(1)O(1)O(n)
雜湊表O(1)O(1)O(1)O(n)
二元搜尋樹O(log n)O(log n)O(log n)O(n)
O(V+E)O(1)O(E)O(V+E)

7. 選型指南:該用哪種資料結構?

How Do You Choose the Right Data Structure?Make the best choice based on scenario needs
What is your use case?
🔍
Fast lookup
Find matching data quickly by key
📊
Preserve order
Data must stay in insertion order or a specific order
🥞
Last in, first out
The most recent item is processed first
🚶
First in, first out
Earlier items are processed first
🌳
Hierarchy
Data has parent-child relationships
🕸️
Complex relationships
Data has many-to-many connections
Quick Reference
Scenario needRecommended structureTime complexity
Random accessArrayO(1)
Fast lookupHash tableO(1)
Ordered lookupBinary search treeO(log n)
Frequent insertion/deletionLinked listO(1)
Undo operationsStackO(1)
Task schedulingQueueO(1)
Decision Flow
Need fast element access?
Yes
Array / Hash table
No
Need frequent insertion and deletion?
Yes
Linked list
No
Need to preserve order?
Yes
Stack / Queue
No
Tree / Graph
你的需求推薦結構原因
按位置快速存取陣列O(1) 隨機存取
頻繁在中間插入刪除鏈結串列O(1) 插入刪除
後進先出(復原、遞迴)堆疊LIFO 語義
先進先出(任務佇列)佇列FIFO 語義
按鍵快速搜尋雜湊表O(1) 平均搜尋
有序資料 + 快速搜尋二元搜尋樹O(log n) 搜尋且保持有序
複雜多對多關係能表達任意節點間的連線

總結

資料結構是程式的骨架。陣列像一排編號置物櫃;鏈結串列像尋寶線索鏈;雜湊表像圖書館索引;像家族族譜;像捷運路線圖。沒有最好的資料結構,只有最合適的。


延伸閱讀

主題推薦資源
資料結構視覺化VisuAlgo
演算法與資料結構《演算法圖解》- Aditya Bhargava
刷題練習LeetCode

下一步

  • 演算法思維:學會用排序、搜尋、遞迴、動態規劃等演算法思維解決問題
  • 程式語言:了解不同程式語言如何實作這些資料結構