contributed by < chi-ming5566
>
以 add_entry()
, find_entry()
, remove_entry()
, swap_pair()
, reverse()
, print_list()
等函式所組成
add_entry()
答案
(a) assert(new_node)
(b) *indirect = new_node
說明
*head
會指向 linked list 的尾端,在其插入一個 value 為 new_value
的 node。**indirect
是用來尋找 linked list (**head) 的尾端,而當 *indirect
找到尾端時, *indirect == NULL
,就會將 new_node
插入linked list。assert
是要確保 new_node
會正確分配記憶體,於是建立第一個 node,所以會直接跳到第 11 行,將 indirect
所存放的 value 當作 adrress,並且更改此 address 存放的 value,將該 value 改為 new_node 的 value。find_entry()
*head
後,傳回存放的值為 value
的 node,用於刪除某一個 node。remove_entry()
說明
**head
找到 node *head
然後刪除。entry
的 pointer,因此以 **indirect
存放此 pointer 的 address。*indirect
指向 entry->next
,就不會有其他 pointer 指向該處。以作業為例:
先執行到第10行,接著將 head
的 address與要刪除的 node 的 address 當作參數,一起傳入remove_entry()
。
head
的 value 是 main
的 head
的 address
indirect
存放 head
存放的 value
讓 *indirect
所存放的值換為 entry->next
,如此便可以達到刪除的目的
swap_pair()
目的:交換一對相鄰的節點,取自 LeetCode: Swap Nodes in Pairs,給定 1->2->3->4,則該回傳 2->1->4->3