# 2020q3 Homework1 (quiz1) ## AA1和AA2 ```cpp= void add_entry(node_t **head, int new_value) { node_t **indirect = head; node_t *new_node = malloc(sizeof(node_t)); new_node->value = new_value; new_node->next = NULL; AA1; while (*indirect) indirect = &(*indirect)->next; AA2; } ``` - ### AA1 如果這邊放```*indirect = new_node;```會把```head```設為```new_node```所以不可能。所以選擇檢查```new_node```的```assert(new_node);``` - ### AA2 這邊要把```new_node```放入linked list中的最後一個節點,所以選擇```*indirect = new_node;``` ## BB1和BB2 ```cpp= node_t *swap_pair(node_t *head) { for (node_t **node = &head; *node && (*node)->next; BB1) { node_t *tmp = *node; BB2; tmp->next = (*node)->next; (*node)->next = tmp; } return head; } ``` - ### BB1 因為這邊要兩兩互換,而且下面```tmp```的變數會暫時除存一個節點的指標,所以在```for```的迴圈中要讓```node```的指標一次跳兩個 - ### BB2 這邊因為上面讓```tmp```存了```node```而下面又使```tmp->next = (*node)->next```所以BB2這行必須要使```tmp```或```node```改變,所以這邊```tmp = tmp->next;```或```(*node) = (*node)->next;```都可以 ## CCC ```cpp= node_t *reverse(node_t *head) { node_t *cursor = NULL; while (head) { node_t *next = head->next; CCC; head = next; } return cursor; } ``` - ### CCC 這邊因為要把linked list 做 reverse ,所以用```cursor```去當新的head並且邊移邊轉。```next```是用來保存```head->next```的節點,讓```head```轉過去後還能夠換到原本的```head->next```。 ## swap_pair改寫 因為```head```只用用來設定```node```而已,所以如果讓```head```來代替```node```的工作則可改寫為: ```cpp= void swap_pair(node_t **head){ for(;*head && (*head)->next;head = &*=(*head)->next->next){ node_t *tmp = *head; *head=(*head)->next; tmp->next = (*head)->next; (*head)->next = tmp; } ``` ## reverse改寫 這邊就單純把```head```變成雙重指標,然後在最後的時候把```*head = cursor``` ```cpp= void reverse(node_t **head){ node_t *cursor = NULL; while(*head){ node_t *next = (*head)->next; (*head)->next = cursor; cursor = *head; *head = next; } *head = cursor; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up