contributed by <ktvexe
>
半夜看還願睡不著,所以試著寫了一下作業。
稍微閱讀程式碼,本來以為是千行的程式,不過後來發現只需要實作 queue.* 的部份,其餘大部份是 UT 的程式碼。
因為長期都使用 server 工作,這次作業回到自己筆電才發現自己筆電的 cscope mapping 壞了,所以紀錄下設定參考連結,讓也是用 vim 的朋友可以參考。
Ref: [Linux] - 將vim打造成source insight
實作 FIFO & LIFO queue,整理一下題目要求,並畫重點,總共七組 function 需要實作,其中有提示 q_insert_tail
and q_size
要 constant time。
q new: Create a new, empty queue.
q free: Free all storage used by a queue.
q insert head: Attempt to insert a new element at the head of the queue (LIFO discipline).
q insert tail: Attempt to insert a new element at the tail of the queue (FIFO discipline).
q remove head: Attempt to remove the element at the head of the queue.
q size: Compute the number of elements in the queue.
q reverse: Reorder the list so that the queue elements are reversed in order. This function should not allocate or free any list elements (either directly or via calls to other functions that allocate or free list elements.) Instead, it should rearrange the existing elements.
提示:
Two of the functions: q_insert_tail and q_size will require some effort on your part to meet the required performance standards. Naive implementations would require O(n) steps for a queue with n elements.
We require that your implementations operate in time O(1)
You can do this by including other fields in the queue_t data structure and managing these values properly as list elements are inserted, removed and reversed.
$ make test
即可執行 UT,過程中大大小小的問題其實都會被抓出來,像是 NULL pointer dereference, memory leak 等等,最後也會顯示通過的測試數量。
其實也有許多類似的 C UT framework 可以協助開發單元測試,例如 googletest。
Ref: C Unit Test Framework 介紹 (Googletest)
像 test 06 我就卡了一下,他顯示 Test of truncated strings
,其實不好懂是做了什麼測試。
所以 grep 一下找到其測資在 traces/trace-06-string.cmd 中。
用 qtest 逐行執行才知道原來是 reverse 少考慮了只有一個 element 的情況。
因為我是用三個 pointer 來做 reverse,只有一個 element 會造成 dereference null pointer。
增加 data member size
& tail
for constant time implementation.
要確認 malloc 使否成功。
linked list 中所有 elements 都需要 free,時間複雜度 。
comments 中特別強調要為 element 的 string malloc 空間,所以一樣要注意 malloc 失敗時,前面成功要到的空間要 free。
同理 q_insert_head
remove_head 有一個參數 sp ,用以回傳被 delete 掉的 string。(deep copy)
注意有限制長度。
回傳 queue 的 size;所以在 add 與 remove 時要記得 maintain size。
使用最基本的三個 pointer 來做 reverse。
所以要注意前面的 pointer 走到 null 時,如果繼續 access 會錯誤。