sysprog2020
目的: 檢驗學員對 linked list 的認知
1
考慮一個單向 linked list,其結構定義為:
已知不存在 circular (環狀結構),接下來將對該單向 linked list 進行下列操作:
add_entry
: 新增節點,當 linked list 沒有內容時,必須由開發者更新指向開頭的指標。因此實際得到 reference,而非 copyremove_entry
: 移去指定節點,指向開頭的指標可能因此變更,所以需要用到 a pointer to a pointer (指標的指標)swap_pair
: 交換一對相鄰的節點,取自 LeetCode: Swap Nodes in Pairs,給定 1->2->3->4
,則該回傳 2->1->4->3
reverse
: 將給定的 linked list 其內節點予以反向,即 1->2->3->4
,則該回傳 4->3->2->1
remove(B)
操作完成後,就會變成 A C 的節點關係。特別注意到 B 這個節點其實還存在於記憶體中,只是我們無法從節點間的關係看出來。於是 "remove" 可解讀為 "take away" (將某物帶走)對應的程式碼如下:
參考執行輸出: (第 1 行是換行符號)
請補完程式碼。
作答區
AA1 = ?
(a)
assert(new_node)
(b)
*indirect = new_node
AA2 = ?
(a)
assert(new_node)
(b)
*indirect = new_node
BB1 = ?
(a)
node = (*node)->next->next
(b)
*node = (*node)->next->next
(c)
*node = ((*node)->next)->next
(d)
*node = &((*node)->next)->next
(e)
node = &(*node)->next->next
(f)
*node = &(*node)->next->next
BB2 = ?
(a)
node = (*node)->next
(b)
node = &(*node)->next
(c)
*node = (*node)->next
(d)
*node = &(*node)->next
(e)
*node = &((*node)->next)
CCC = ?
(a)
cursor = head; head->next = cursor
(b)
head->next = cursor; cursor = head
(c)
cursor = head
(d)
head->next = cursor
(e)
head->next->next = cursor; cursor->next = head
(f)
cursor->next = head; head->next->next = cursor
延伸問題:
swap_pair
和 reverse
對於指標的操作方式顯然異於 add_entry
及 remove_entry
,需要額外做 head = ...
的更新,請用指標的指標來改寫,並避免回傳指標;reverse
,注意,你可能因此需要建立新的函式,如 rev_recursive
,隨後在 reverse
函式中呼叫 rev_recursive
;