contributed by < robertlin0401
>
linux2021
node_t
加入 linked list 的前端node_t
:表指向欲加入目標 linked list 的新 node 的指標list
:表指向目標 linked list 的第一個 node 的指標的指標head
表指向第一個 node 的指標
*list
,即 head
,賦值給 node_t->next
,因此 node_t->next
將指向 head
所指的 node_A
,結果如下
*list
,即 head
,改成指向 node_t
,結果如下
right
所指向的 linked list,串接(concatenate)在 *left
所指向的目標 linked list 尾端left
:表指向目標 linked list 的第一個 node 的指標的指標right
:表欲串接在目標 linked list 尾端的 linked list 的第一個 node 的指標head
表指向目標 linked list 的第一個 node 的指標
*left
串列的尾端 node 的 next 指標的指標,步驟如下
*left
即 head
,指向 node_A
,並非 NULL,因此將 left
向前移動,改成指向 node_A->next
的指標
*left
仍非 NULL,因此繼續將 left
向前移動,改成指向 node_B->next
的指標
*left
為 NULL ,迴圈終止&((*left)->next)
,其中,(*left)->next
為下一個 node 的指標*left
,即 node_B->next
,改成欲串接的 linked list 的第一個 node 的指標 right
,由此兩串列得以成功串接,結果如下
補充說明:Array vs. Linked List
list
:表目標串列的第一個 node 的指標的指標!*list
成立時,表示當前串列的元素個數為 0 個,無法再進行分割,此條件符合上述 quicksort 基本概念第 2 點pivot
,因此 pivot 取的是串列的第一個元素left
,與由較 pivot 大的 node 所組成的子串列 right
list_add_node_t
函式的第一個引數 n->value > value ? AAA : BBB
為指定當前 node n
應加入的 linked list 的指標的指標,其中,value
為 pivot 之值AAA
為 n->value > value
成立時 node n
應加入的 linked list 的指標的指標,因此 AAA
應填入 &right
BBB
為 n->value > value
不成立時 node n
應加入的 linked list 的指標的指標,因此 BBB
應填入 &left
left
、right
兩子串列做 quicksort*list
,即完整串列的第一個 node 的指標
CCC
應填入 list_concat(&result, pivot); list_concat(&result, right)
,說明可參考上述 quicksort 的補充說明中 Linked List 表示部分random()
方法是一種 Pseudo-Random Number Generator (PRNG),它會根據 srandom()
所設定的 seed 來生成隨機數,當未設定 seed 時,預設值為 1
節錄自 random(3) man page description:
The srandom() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by random(). These sequences are repeatable by calling srandom() with the same seed value. If no seed value is provided, the random() function is automatically seeded with a value of 1.
節錄自 random(4) man page description:
- The character special files /dev/random and /dev/urandom (present since Linux 1.3.30) provide an interface to the kernel's random number generator.
- The random number generator gathers environmental noise from device drivers and other sources into an entropy pool.
- Linux 3.17 and later provides the simpler and safer getrandom(2) interface which requires no special files
getrandom()
的系統呼叫可從熵池中隨機讀取指定數量的位元組補充說明:為何不全部使用熵池的資料作為亂數資料?
因為熵池大小有限,若全部自熵池取用,在需要取得較大量的亂數的情形,可能會發生可取得的資料量不足的問題,因此只取用其中 4 bytes 作為 PRNG 的 seed
getrandom()
的系統呼叫從熵池中隨機讀取 4 個位元組,即 seed 所需的整數型態的大小getrandom()
的結果是否成功,若失敗則直接將 result
(-1)做為 seed 使用list
:表目標串列的第一個 node 的指標的指標elements
:表目標串列的 node 總數/長度MAX_LEVELS
,其意義相似於 recursive 版本中的遞迴呼叫深度,作為限制其記憶體使用量
list2arr
的實作如下:
MAX_LEVELS
,其中,SWAP
的實作如下:
list_less
與 list_greater
兩 lists 進行初始化,分別作為鏈結比 pivot 小與比 pivot 大的 nodes 的 sublist
list_less
的尾端,較 pivot 大者則是會從原串列刪除並加入 list_greater
的前端,因此比較皆完成之後,原串列會變為空串列
list_less
與 list_greater
兩 sublists 進行遞迴排序pivot
加入當前為空的原串列的前端,並將 list_less
加入原串列的前端、 list_greater
加入原串列的尾端
:question:延伸問題:為何要用指標,而非直接將兩數相減?
仔細觀察可以發現其參數型態為 void *
,代表此函式可應用於非整數型態變數的整數減法,例如:記憶體位址(指標型態)的減法操作