Kodewick
開始學 →
鏈結串列:結點和 next9 / 52

鏈結串列:結點和 next

第 9 課,共 52 課 · 第 2 部分 · 名字、list 和鏈結串列 · 約 15 分鐘

鏈結串列把每個值放在自己的結點物件裡,用 next 指向下一個結點;從 head 出發用 while cur 走到 None,在最前面加一個是 O(1),但要第 i 個就得走 i 步。

第 2 課算過:往 list 最前面插 10 萬次,一共要挪大約 50 億次,因為格子必須挨著。鏈結串列換了個放法:每個值放在自己的結點物件裡,結點散在記憶體各處,每個結點用一個 next 指著下一個。往最前面加一個,只要造一個結點、改一個引用,不管鏈結串列有 10 個還是 10 萬個結點。代價是沒有 a[i] 了:要第 i 個,得從頭走 i 步。

結點:一個值加一個 next

結點是一個很小的物件:val 放值,next 指著下一個結點,最後一個的 next 是 None。整個鏈結串列只要記住第一個結點,叫 head。這就是第 1 課的「引用」:next 只是結點物件上的一個名字,指著另一個物件。點「播放」一步步看:

class Node:    def __init__(self, val, next=None):        self.val = val        self.next = next c = Node(9)b = Node(7, c)a = Node(3, b)head = aprint(head.val, head.next.val, head.next.next.val)print(head.next.next.next)
從後往前造 3 個結點:每個的 next 指著後一個;head 記住第一個,順著 next 就能拿到全部

head.next.next.next 是最後一個結點 9 的 next,也就是 None。名字 a、b、c 只是造的時候方便,鏈結串列本身只靠 next 連著:

main.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7second = head.next8print(second.val, second.next.val)9print(head.next is second)
輸出
7 9
True
單選

鏈結串列最後一個結點的 next 是什麼?

猜輸出猜錯也沒關係

這段程式印出什麼?

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7print(head.next.next.val - head.next.val)
排順序拖動或點箭頭排順序

把造結點的三行排好,讓程式印出 3 7 9。造一個結點時,它的 next 要指的那個結點得已經有了。

  1. b = Node(7, c)
  2. a = Node(3, b)
  3. c = Node(9)
要顯示
3 7 9

遍歷:while cur

走一遍鏈結串列的寫法幾乎永遠是這三行:

head↓cur↓
3a
7b
9c
None
1cur = head2while cur:3    print(cur.val)4    cur = cur.next

cur 從 head 出發,每輪印出一個再 cur = cur.next;走到 None,while cur 就停了

為什麼要另用一個 cur,不直接移動 head?head 一往後走,前面的結點就沒有引用指著了:鏈結串列丟了一截,Python 還會把它們回收。

main.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7 8cur = head9while cur:10    print(cur.val, end=" ")11    cur = cur.next12print()13 14total, count = 0, 015cur = head16while cur:17    total += cur.val18    count += 119    cur = cur.next20print("和", total, "個數", count)21print(head.val)
輸出
3 7 9 
和 19 個數 3
3
猜輸出猜錯也沒關係

條件換成了 while cur.next,印出什麼?

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7cur = head8count = 09while cur.next:10    count += 111    cur = cur.next12print(count, cur.val)
填空點一個填進空格,再點空格可以拿回來

選一個填進空格,讓 cur 一個結點一個結點往後走,算出 3 + 7 + 9。

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6head = Node(3, Node(7, Node(9)))7total = 08cur = head9while cur:10    total += cur.val11    cur = 12print(total)
練習 1

它在第幾個

補全 find(head, x):回傳值 x 第一次出現的位置(從 0 數),沒有就返回 -1。

要顯示
0 1 2 -1
-1
exercise1.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6def find(head, x):7    # cur 從 head 走,i 跟著數8    return -19 10head = Node(3, Node(7, Node(9, Node(7))))11print(find(head, 3), find(head, 7), find(head, 9), find(head, 5))12print(find(None, 3))
輸出
點「執行」或按 Ctrl+Enter

一個鏈結串列類:__iter__ 和 __len__

把 head 包進一個類裡,再給它兩個特殊方法,就能像 list 一樣用 for、list()、len():

  • __iter__ 寫成生成器:函數裡有 yield,每被要一個值,就往下跑到下一個 yield,把 cur.val 交出去,下次從這裡接著走。
  • __len__ 返回自己記著的 size:每加一個結點就加 1,len(L) 就是 O(1),不用每次走一遍。

往最前面加一個(push_front)只改一個引用:

head↓
1d
3a
7b
9c
None

push_front(1):新結點的 next 指著原來的第一個,再讓 head 指著新結點;只改了 1 個引用
main.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6class LinkedList:7    def __init__(self):8        self.head = None9        self.size = 010 11    def push_front(self, val):12        self.head = Node(val, self.head)13        self.size += 114 15    def __iter__(self):16        cur = self.head17        while cur:18            yield cur.val19            cur = cur.next20 21    def __len__(self):22        return self.size23 24L = LinkedList()25for x in [9, 7, 3, 1]:26    L.push_front(x)27print(list(L), len(L))28for v in L:29    print(v, end=" ")30print()31print(sum(L), max(L), 7 in L, 8 in L)
輸出
[1, 3, 7, 9] 4
1 3 7 9 
20 9 True False

有了 __iter__,sum、max、in 都能直接用。但別忘了它們背後都是從 head 走一遍:7 in L 是 O(n)。

猜輸出猜錯也沒關係

push_front 三次以後,印出什麼?

1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6class LinkedList:7    def __init__(self):8        self.head = None9        self.size = 010 11    def push_front(self, val):12        self.head = Node(val, self.head)13        self.size += 114 15    def __iter__(self):16        cur = self.head17        while cur:18            yield cur.val19            cur = cur.next20 21    def __len__(self):22        return self.size23 24L = LinkedList()25for x in [1, 2, 3]:26    L.push_front(x)27print(list(L), len(L))

代價:沒有 a[i]

操作list鏈結串列(只記著 head)
取第 i 個O(1)O(i):從頭走 i 步
在最前面加O(n):全部往後挪O(1):改一個引用
在末尾加攤還 O(1)O(n) 先走到最後;另記著 tail 就是 O(1)
lenO(1)O(n) 走一遍;自己記著 size 就是 O(1)
x in …O(n)O(n)
每個元素另外要的一個引用一個結點物件:val、next 兩個引用,加上物件本身的開銷

鏈結串列的長處只有一條:手裡已經拿著某個結點時,在它附近插入、刪除是 O(1)(下一課)。別的地方大多不如 list。

面試裡: 鏈結串列題給的都是 class ListNode: def __init__(self, val=0, next=None),只給你 head。先在紙上畫出幾個結點和箭頭,再寫 while cur;特別想清楚兩頭:空鏈結串列(head 是 None)和最後一個結點。

單選

鏈結串列是 head → 5 → 1 → 4 → 2。cur 從 head 出發(站在 5 上),要做幾次 cur = cur.next 才站到 4 上?

多選可以選多個

鏈結串列只記著 head,沒有 size、也沒有 tail。下面哪些要 O(n)?(可以選好幾個)

練習 2

記著 tail,末尾加也是 O(1)

給 LinkedList 補全 append(val):用 self.tail 記著最後一個結點,在末尾接一個新結點,不用從頭走。注意空鏈結串列時 head 和 tail 都要指著新結點。

要顯示
[3, 7, 9] 3
3 9 None
exercise2.py
1class Node:2    def __init__(self, val, next=None):3        self.val = val4        self.next = next5 6class LinkedList:7    def __init__(self):8        self.head = None9        self.tail = None10        self.size = 011 12    def append(self, val):13        # 空鏈結串列:head、tail 都是新結點;否則接在 tail 後面,tail 往後挪14        pass15 16    def __iter__(self):17        cur = self.head18        while cur:19            yield cur.val20            cur = cur.next21 22    def __len__(self):23        return self.size24 25L = LinkedList()26for x in [3, 7, 9]:27    L.append(x)28print(list(L), len(L))29print(L.head.val, L.tail.val, L.tail.next)
輸出
點「執行」或按 Ctrl+Enter

工作裡這樣寫

Python 的標準庫裡沒有單鏈表型別,工作裡也很少自己寫:只在末尾進出用 list,兩頭進出用 collections.deque(它在 CPython 裡是一串 64 格的小塊用雙向鏈結串列連起來,兩頭 O(1),按下標取中間是 O(n))。鏈結串列主要出現在面試題裡,以及別的結構內部:LRU 快取(第 6 課)、雜湊表的拉鏈、圖的鄰接表。

刷題時,先寫兩個小工具,用 list 造鏈結串列、把鏈結串列變回 list 來印出,除錯省很多事:

main.py
1class ListNode:2    def __init__(self, val=0, next=None):3        self.val = val4        self.next = next5 6def from_list(vals):7    head = None8    for v in reversed(vals):9        head = ListNode(v, head)10    return head11 12def to_list(head):13    out = []14    while head:              # head 只是這個函數裡的名字,移動它不影響外面15        out.append(head.val)16        head = head.next17    return out18 19h = from_list([1, 2, 3, 4])20print(to_list(h))21print(to_list(from_list([])))22print(h.val)
輸出
[1, 2, 3, 4]
[]
1
單選

collections.deque 在兩頭進出、按下標取中間,各是多快?

小結

這一課帶走

鏈結串列:結點靠 next 一個指一個

  • 結點 = val + next;最後一個的 next 是 None;head 記住第一個
  • 遍歷用另一個 cur:while cur 處理每個,while cur.next 停在最後一個
  • 最前面加一個只改一個引用:O(1);取第 i 個要走 i 步:O(n)
  • __iter__ 用生成器 yield,__len__ 返回自己記著的 size
1cur = head2while cur:3    print(cur.val)4    cur = cur.next5self.head = Node(val, self.head)   # push_front