or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing
xxxxxxxxxx
2023q1 Homework4 (quiz4)
contributed by <
LiChiiiii
>測驗一
在測驗一提供的程式碼中定義
對照 rb.h 之巨集的使用,展開
rb_gen(static, ex_, ex_t, ex_node_t, ex_link, ex_cmp)
巨集可以得到插入、刪除等功能之函式。推敲其設計思維
tree_insert()
將巨集
x_attr void x_prefix##insert(x_rbt_type *rbtree, x_type *node)
展開為static void tree_insert (tree_t *rbtree, node_t *node)
,此函式將新節點插入紅黑樹中,主要有三個步驟:舉個例子來說,現在有一個紅黑樹。
我們想插入新的節點
3
,會先用 BST 的概念尋找插入的位置。3
與7
比較,紀錄 cmp = -1 ,並往左進行下一層尋找。3
與2
比較,紀錄 cmp = 1 ,並往右進行下一層尋找。3
與5
比較,紀錄 cmp = -1 ,並往左進行下一層尋找,得到 NULL 跳出迴圈,把插入位置指向此節點,也就是pathp->node = node
。由於在尋找插入的位置的過程中,有依序紀錄經過每個節點及其 cmp 至名為 path 的陣列,因此當找到插入位置的同時,也得到了以下陣列 path 。
接下來將 pathp 反向回去,判斷每個 pathp 的 cmp 值來檢查是否需要旋轉。
如果 cmp < 0 ,且出現左邊狀況則進行旋轉成右邊的樣子。
如果 cmp >= 0 ,
最後將根節點設為黑色。
tree_remove()
將巨集
x_attr void x_prefix##remove(x_rbt_type *rbtree, x_type *node)
展開為static void tree_remove(tree_t *rbtree, node_t *node)
,此函式用於刪除紅黑樹中的節點,跟tree_insert()
一樣的方式去尋找要刪除的節點,只是額外加上if(cmp==0)
,若條件式成立,則表示找到要刪除的節點,接著就是找出節點的 successor ,來為交換做準備。舉個例子來說,現在有一個紅黑樹,我想刪除節點
2
。可以得到這個 path 陣列。
在
cmp == 0
時,代表找到想刪除的節點,也就是找到節點2
,會設定 pathp->cmp = 1 ,並尋找此節點的 successor 。因此 path 陣列會變成
測驗二
測驗三