# 2019q1 Homework1 (lab0) :::danger 注意看作業要求,符合對應格式 ::: ## 作業要求 - 完成 `queue.c` 中的 function 實作 - 解釋 qtest 的運作原理 ## 執行環境 ``` $ uname -a Linux ubuntu 4.15.0-45-generic #48~16.04.1-Ubuntu SMP Tue Jan 29 18:03:48 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux ``` ## 實作 queue ### q_reverse 從頭開始遍歷 queue,記錄好 prev(上一個) 跟 next(下一個), 每次的操作就是將 `now->next = prev`,將整個 queue 反過來 ```cpp void q_reverse(queue_t *q) { if (!q) return; list_ele_t *now = q->head; list_ele_t *prev = NULL; list_ele_t *next; list_ele_t *tmp; tmp = q->head; q->head = q->tail; q->tail = tmp; while (now) { next = now->next; now->next = prev; prev = now; now = next; } } ``` ### 忘記 free 檢查 malloc 失敗後,容易忘記 free 掉之前 malloc 的空間 ```cpp newh = malloc(sizeof(list_ele_t)); if (!newh) return false; news = malloc(strlen(s) + 1); if (!news) { free(newh); // <-- 這裡 return false; } ``` 更新: 其實可以利用 `free(NULL)` 不會出錯的特性,將 code 改為 ```cpp newh = malloc(sizeof(list_ele_t)); news = malloc(strlen(s) + 1); if (!newh || !news) { free(newh); free(news); return false; } ``` ## qtest
×
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