雙向鏈結串列和迴圈鏈結串列
雙向鏈結串列的結點有 next 和 prev 兩個指標,能往回走,插入要按順序改 4 個指標;迴圈鏈結串列的尾結點指回頭,std::list 就是帶哨兵的雙向迴圈鏈結串列。
單鏈表只能往後走:站在一個結點上,想找它前一個,只能從頭再走一遍。雙向鏈結串列給每個結點多一個指向前一個的指標;迴圈鏈結串列讓最後一個結點指回第一個。這一課把兩種都用 C++ 手寫出來,再看 STL 的 std::list:它正是兩種合在一起的樣子。
雙向鏈結串列的結點
1struct DNode {2 int val;3 DNode* prev; // 前一個(教材裡常叫 prior)4 DNode* next; // 後一個5 DNode(int v) : val(v), prev(nullptr), next(nullptr) {}6};
多一個指標,每個結點多佔 8 位元組,換來的是:站在任何一個結點上,前後都能 O(1) 走到;拿著一個結點,刪掉它也不用從頭找前一個。
第一個結點的 prev 和最後一個結點的 next 都是 nullptr。三個結點連起來是這樣:
在雙向鏈結串列裡站在結點 p 上,找它的前一個結點要多久?
p->prev 一步就到,O(1)。單鏈表沒有 prev,才要從頭再走一遍,O(n)。插入:4 個指標,順序要對
在 p 後面插入新結點 s(p 後面原來是 q)。要改的有 4 個指標:
s->next = p->next;:s 先連上後面的 qp->next->prev = s;:q 往回指 ss->prev = p;:s 往回指 pp->next = s;:最後才改 p 往後的指標
關鍵是第 4 步要在 1、2 之後:1、2 都要通過 p->next 找到 q,先改了 p->next,q 就找不到了。和單鏈表一樣,還是「先連後面,再改前面」。
p↓q↓1#include <iostream>2using namespace std;3 4struct DNode {5 int val;6 DNode* prev;7 DNode* next;8 DNode(int v) : val(v), prev(nullptr), next(nullptr) {}9};10 11void show(DNode* head) {12 for (DNode* p = head; p != nullptr; p = p->next)13 cout << p->val << " ";14 cout << "\n";15}16 17void clear(DNode* head) {18 while (head != nullptr) {19 DNode* next = head->next;20 delete head;21 head = next;22 }23}24 25int main() {26 DNode* p = new DNode(3);27 DNode* q = new DNode(7);28 p->next = q;29 q->prev = p;30 31 DNode* s = new DNode(5);32 s->next = p->next; // 133 p->next->prev = s; // 234 s->prev = p; // 335 p->next = s; // 436 show(p);37 // 往回走:從 q 一路 prev 回去38 for (DNode* r = q; r != nullptr; r = r->prev)39 cout << r->val << " ";40 cout << "\n";41 clear(p);42 return 0;43}
3 5 7 7 5 3
(要是 p 就是最後一個結點,p->next 是 nullptr,沒有 q:第 2 步要先判斷 if (p->next != nullptr)。折起來的 clear 順著 next 把結點一個個 delete 掉。)
把這 4 行排好:在 p(結點 1)後面插入 s(結點 2),讓程式正著印出 1 2 3、倒著印出 3 2 1。
s->next = p->next;s->prev = p;p->next->prev = s;p->next = s;
1 2 3 3 2 1
p->next 找到結點 3,所以 p->next = s; 一定放在它們後面;s->prev = p; 放在哪兒都行。先改了 p->next,結點 3 就找不到了。雙向鏈結串列:在 p 後面插入
✓補全 insert_after:在 p 後面插入 x,p 後面一定還有結點。按順序改 4 個指標,讓程式正著、倒著各印出一遍。
10 20 30 30 20 10
1#include <iostream>2using namespace std;3 4struct DNode {5 int val;6 DNode* prev;7 DNode* next;8 DNode(int v) : val(v), prev(nullptr), next(nullptr) {}9};10 11void show(DNode* head) {12 for (DNode* p = head; p != nullptr; p = p->next)13 cout << p->val << " ";14 cout << "\n";15}16 17void clear(DNode* head) {18 while (head != nullptr) {19 DNode* next = head->next;20 delete head;21 head = next;22 }23}24 25void insert_after(DNode* p, int x) {26 DNode* s = new DNode(x);27 // 1 s->next 2 p->next->prev 3 s->prev 4 p->next28}29 30int main() {31 DNode* a = new DNode(10);32 DNode* b = new DNode(30);33 a->next = b;34 b->prev = a;35 insert_after(a, 20);36 show(a);37 for (DNode* r = b; r != nullptr; r = r->prev)38 cout << r->val << " ";39 cout << "\n";40 clear(a);41 return 0;42}
刪除:前後兩個都要改
刪除 p 後面的結點 q:
1DNode* q = p->next;2p->next = q->next;3if (q->next != nullptr)4 q->next->prev = p;5delete q;
只有 2 個指標要改,再 delete。同樣,delete 之前要先把指標都接好。(圖裡的 free(q),在 C++ 裡就是 delete q。)
刪掉 a 後面的 b 之後,印出什麼?
1#include <iostream>2using namespace std;3 4struct DNode {5 int val;6 DNode* prev;7 DNode* next;8 DNode(int v) : val(v), prev(nullptr), next(nullptr) {}9};10 11int main() {12 DNode a(1), b(2), c(3);13 a.next = &b; b.prev = &a; b.next = &c; c.prev = &b;14 DNode* p = &a;15 DNode* q = p->next;16 p->next = q->next;17 q->next->prev = p;18 cout << a.next->val << " " << c.prev->val << "\n";19 return 0;20}
p->next = q->next 讓 a 往後直接指 c;q->next->prev = p 讓 c 往回直接指 a。兩個方向都跳過了 b:印出 3 1。只改一個方向,往回走時還會走到已經刪掉的 b。要刪的 q 正好是最後一個結點(q->next 是 nullptr)。哪一句不先判斷就會出錯?
q->next 是 nullptr,q->next->prev 就是通過空指標去改東西,程式會出錯(這裡的引擎會停在那一行)。所以要先寫 if (q->next != nullptr)。p->next = q->next; 只是把 nullptr 抄給 p,沒問題。迴圈鏈結串列:最後一個指回頭
把最後一個結點的 next 從 nullptr 改成指向第一個,就成了迴圈鏈結串列。從任何一個結點出發,都能走遍所有結點。
head↓這時遍歷不能再等 nullptr(永遠等不到),要等「又回到出發的那個」:
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int main() {11 Node* c = new Node(9);12 Node* head = new Node(3, new Node(7, c));13 c->next = head; // 最後一個指回頭14 15 Node* p = head;16 do {17 cout << p->val << " ";18 p = p->next;19 } while (p != head); // 回到出發點就停20 cout << "\n";21 22 c->next = nullptr; // 先斷開環,再一個個 delete23 while (head != nullptr) {24 Node* next = head->next;25 delete head;26 head = next;27 }28 return 0;29}
3 7 9
用 do … while 是因為一開始 p 就等於 head,要先走一步再判斷。釋放時也要小心:直接套 while (head != nullptr) 會繞著環一直 delete 下去,先把環斷開。
實際用迴圈單鏈表時,常常不存 head,只存一個尾指標 rear(指著最後一個結點):第一個結點就是 rear->next,所以在頭上插入、在尾上插入都是 O(1)。
| 單鏈表 | 雙向鏈結串列 | 迴圈鏈結串列 | |
|---|---|---|---|
| 每個結點 | val、next | val、prev、next | 同單鏈表,尾巴指回頭 |
| 拿著結點 x,刪掉它 | O(n):先找前一個 | O(1):x->prev 就是 | O(n):繞一圈找前一個 |
| 能不能往回走 | 不能 | 能 | 不能,但能繞回來 |
| 遍歷到哪停 | p == nullptr | p == nullptr(或哨兵) | p == head(回到起點) |
考試常考: 判斷空表,單鏈表(帶頭結點 L)是 L->next == nullptr,迴圈單鏈表是 L->next == L;雙向鏈結串列插入的 4 步順序,最後一步一定是改 p->next。
把 do … while 換成普通的 while,這段程式印出幾?
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int main() {11 Node c(9), b(7, &c), a(3, &b);12 c.next = &a;13 Node* head = &a;14 Node* p = head;15 int n = 0;16 while (p != head) {17 n++;18 p = p->next;19 }20 cout << n << "\n";21 return 0;22}
p 一開始就等於 head,while 先判斷,條件一上來就不成立,迴圈一次都不進:印出 0。所以繞一圈要用 do … while,先走一步再判斷。帶頭結點的迴圈單鏈表 L,怎樣判斷它是空表?
L->next == L。L->next == nullptr 是普通單鏈表的判空。一個不帶頭結點的迴圈單鏈表只存了尾指標 rear。第一個結點是哪個?
rear->next。有了 rear,頭和尾都能一步拿到:這就是隻存尾指標的好處。迴圈鏈結串列有幾個
✓補全 count:從 head 出發繞一圈,數一共幾個結點(鏈結串列不為空)。
4
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int count(Node* head) {11 int n = 0;12 Node* p = head;13 // do … while:走到又回到 head14 return n;15}16 17int main() {18 Node* last = new Node(4);19 Node* head = new Node(1, new Node(2, new Node(3, last)));20 last->next = head;21 cout << count(head) << "\n";22 last->next = nullptr;23 while (head != nullptr) {24 Node* next = head->next;25 delete head;26 head = next;27 }28 return 0;29}
用 STL 寫
std::list 就是一條雙向迴圈鏈結串列,外加一個哨兵結點(g++ 的寫法):哨兵不存資料,它的 next 是第一個、prev 是最後一個;end() 指的就是這個哨兵,所以 --end() 是最後一個元素。有了哨兵,每個真結點前後都有結點,插入、刪除裡那句 if (p->next != nullptr) 就不用寫了。
它最有用的兩件事:
splice:把結點從一處摘下來接到另一處(同一個 list 裡,或另一個 list 裡),只改指標,不復制、不new也不delete,一個結點或整個 list 都是 O(1)。- 迭代器不失效:插入、刪除、
splice別的元素,指著某個元素的迭代器一直有效(結點沒動,只是前後指標變了)。只有那個元素自己被erase了,它的迭代器才作廢。vector不一樣:插入可能整塊搬家,原來的迭代器全部作廢。
1#include <iostream>2#include <list>3using namespace std;4 5void show(const list<int>& lst) {6 for (int x : lst)7 cout << x << " ";8 cout << "\n";9}10 11int main() {12 list<int> a = {1, 2, 3};13 list<int> b = {7, 8, 9};14 auto it = a.begin();15 ++it; // it 指著 216 17 for (auto r = a.rbegin(); r != a.rend(); ++r)18 cout << *r << " "; // 倒著走:靠 prev19 cout << "\n";20 cout << *(--a.end()) << "\n"; // end() 是哨兵,它前一個是最後一個21 22 a.splice(it, b); // b 整串接到 2 前面:O(1)23 show(a);24 cout << b.size() << " " << *it << "\n"; // b 空了;it 還指著 225 26 a.splice(a.begin(), a, it); // 把 2 這一個結點挪到最前面27 show(a);28 cout << *it << "\n"; // 還是 229 return 0;30}
3 2 1 3 1 7 8 9 2 3 0 2 2 1 7 8 9 3 2
把 unordered_map 和 list 拼起來,就是面試裡幾乎必考的 LRU 快取(最多放 cap 個,滿了扔掉最久沒用的;get、put 都要 O(1)):list 從最近用過排到最久沒用,unordered_map 記著每個 key 在 list 裡的迭代器。用到一個 key,就 splice 到最前面;滿了,刪 list 最後一個。迭代器不失效,map 裡存的位置才一直能用。
1#include <iostream>2#include <list>3#include <unordered_map>4#include <utility>5using namespace std;6 7class LRUCache {8 int cap;9 list<pair<int, int>> items; // (key, val):前面最近用過10 unordered_map<int, list<pair<int, int>>::iterator> pos; // key -> 在 items 裡的位置11public:12 LRUCache(int c) : cap(c) {}13 14 int get(int key) {15 auto f = pos.find(key);16 if (f == pos.end())17 return -1;18 items.splice(items.begin(), items, f->second); // 用過:挪到最前面19 return f->second->second;20 }21 22 void put(int key, int val) {23 auto f = pos.find(key);24 if (f != pos.end()) {25 f->second->second = val;26 items.splice(items.begin(), items, f->second);27 return;28 }29 if ((int)items.size() == cap) {30 pos.erase(items.back().first); // 最久沒用的:最後一個31 items.pop_back();32 }33 items.push_front(make_pair(key, val));34 pos[key] = items.begin();35 }36};37 38int main() {39 LRUCache c(2);40 c.put(1, 1);41 c.put(2, 2);42 cout << c.get(1) << " ";43 c.put(3, 3); // 滿了:2 最久沒用,刪掉44 cout << c.get(2) << " ";45 c.put(4, 4); // 滿了:1 最久沒用,刪掉46 cout << c.get(1) << " " << c.get(3) << " " << c.get(4) << "\n";47 return 0;48}
1 -1 -1 3 4
std::list 操作 | 代價 | 說明 |
|---|---|---|
push_front / push_back / pop_front / pop_back | O(1) | 兩頭都快 |
insert(it, x) / erase(it) | O(1) | 已經有迭代器時 |
splice 一個結點或整個 list | O(1) | 只改指標 |
--end()、rbegin() 倒著走 | O(1) 每步 | 靠 prev |
| 找某個值、走到第 i 個 | O(n) | 沒有下標 |
面試裡: LRU 快取(力扣 146)的標準答案就是上面這樣:雙向鏈結串列 + 雜湊表,get、put 都是 O(1)。面試官可能讓你不用 std::list、手寫雙向鏈結串列,那就照這一課的 DNode 寫,兩頭各放一個哨兵,插入、刪除就不用判 nullptr。
splice 把 2 這個結點挪到最後,再印出整條 list 和 *it。顯示什麼?
1#include <iostream>2#include <list>3using namespace std;4 5int main() {6 list<int> a = {1, 2, 3, 4};7 auto it = a.begin();8 ++it;9 a.splice(a.end(), a, it);10 for (int x : a)11 cout << x << " ";12 cout << *it << "\n";13 return 0;14}
it 指著 2;splice(a.end(), a, it) 把這個結點摘下來接到最後,list 變成 1 3 4 2。結點本身沒動,只是前後指標變了,所以 it 還有效,還指著 2:最後印出 1 3 4 2 2。這一關的 LRUCache c(2) 依次做 put(1, 1)、put(2, 2)、get(1)、put(3, 3)。put(3, 3) 時被扔掉的是哪個 key?
get(1) 把 1 挪到最前面,list 從近到遠是 1 2。放 3 時已經滿了(cap = 2),扔掉最久沒用的、也就是最後一個:2。之後 list 是 3 1。小結
雙向鏈結串列能往回走;迴圈鏈結串列首尾相連;std::list 兩樣都是
- 雙向插入 4 步:s->next、p->next->prev、s->prev,最後 p->next
- 雙向刪除:前後兩個方向都要跳過它,再 delete
- 迴圈鏈結串列遍歷:回到出發點才停,用 do … while
- std::list:帶哨兵的雙向迴圈鏈結串列;splice O(1),迭代器不失效
1s->next = p->next;2p->next->prev = s;3s->prev = p;4p->next = s;5lst.splice(lst.begin(), lst, it); // 挪到最前面