contributed by < Jadezzz
>
根據作業要求, q_insert_tail
以及 q_size
函數需要達到 的時間複雜度,所以對 queue_t
的欄位做以下修改:
tail
指標記錄 queue 最末端的元素size
記錄 queue 當前的大小(因爲 size 不爲負數,使用 unsigned long
能記錄最多 個元素)malloc()
執行失敗,則回傳 NULL
q
,如果爲 NULL
則回傳 false
false
q
,如果爲 NULL
則回傳 false
false
false
oldh
NULL
oldh
的下一個元素oldh->value
的記憶體空間釋放oldh
本身的記憶體空間釋放q
爲 NULL
,直接回傳NULL
或空,直接回傳head
和 tail
由於題目要求 q_sort
參考 Lisked List Sort 使用 Recursive 的方式進行 split 以及 merge
執行 make test
後測試結果,發現 test case 中 只有第 15 個 出現 Segmentation Fault,其餘正常
查看 trace 後發現第 15 個 test case 會插入 2000000 個元素後進行排序,推測是使用 Recursive 導致 Stack Overflow 造成 Segmentation Fault
使用 make valgrind
,運用 Valgrind 工具檢查記憶體使用狀況,發現果然是 Stack Overflow
將 merge 的部分改用 Iterative 方式,減少 stack 的使用量,避免 stack overflow
head
記錄 merge 過後的 linked list 起始位置cur
記錄 merge 過程中 linked list 的最後一個 element 位置l1
和 l2
都還沒有被使用完時,將 value 比較小的接在 cur
後l1
/l2
其中一個用完時,將剩下的接在 cur
後使用 natsort 方式實作
C99 規格書,7.21.4 Comparison functions 可以找到 strcmp
比較的原則:
The sign of a nonzero value returned by the comparison functions memcmp, strcmp,
and strncmp is determined by the sign of the difference between the values of the first
pair of characters (both interpreted as unsigned char) that differ in the objects being
compared.
也就是說,strcmp
比較的原則是將兩個 string 內容以 unsigned char
比對,當碰到不一樣的 unsigned char
時,就返回 unsigned char
相差的值
e.g.
返回值爲 -1,因爲 a 的 ASCII code - b 的 ASCII code 結果爲 -1
以爲這樣的機制,所以考慮以下的三個子串 rfc1.txt
、rfc2086.txt
、rfc822.txt
如果以 strcmp
作爲排序依據,則結果爲:
rfc1.txt
< rfc2086.txt
< rfc822.txt
但是通常我們希望 數字部分能按照大小進行排列,所以使用 natural sort
natural sort 的機制是:
Strings are sorted as usual, except that decimal integer substrings are compared on their numeric value.
所以考慮上述的子串,使用 natural sort 結果爲:
rfc1.txt
< rfc822.txt
< rfc2086.txt
strnatcmp.h
和 strnatcmp.c
並加入專案目錄strnatcmp.c
被編譯
q_sort()
函數中,變更原 strcmp
爲 strnatcmp