There are N courses in a computer science department. Each course contains two data fields: (1) number (3 digits) as key and (2) name (string). Insert the following 4 courses:
123 Data Structure / 234 Software Engineering / 345 Programming Language / 233 Compiler
into each of the 5 data structures below, and draw a sketch for each. Note that you should draw each and every data field, including pointers. Null pointers should be specified as ●.
(1) array (5%) (2) doubly-linked list (need a dummy node) (5%) (3) red-black tree (need a color field) (5%) (4) chained hashing with a hash table of size 11 and a hash function \(h\) where \(h(\text{key})=\text{key}\bmod11\) (5%) (5) heap (5%)
(1) array 依插入順序放進 index 0、1、2、3,每格兩個欄位(key、name)
(2) doubly-linked list(dummy node) dummy 不放資料,尾端接在最後;每個 node 有 prev、key、name、next,第一個資料 node 的 prev 指回 dummy,dummy.prev 與最後一個 node 的 next 是 null(●)
(3) red-black tree 每個 node 有 left、key、name、color、right
插 123:root,塗黑 → 插 234:紅,在 123 右邊
插 345:紅,在 234 右邊,parent 234 是紅且 uncle 為 null(黑) → RR case,對 123 左旋,234 塗黑、123 塗紅
→
插 233:\(233\lt234\) → 往左 \(233\gt123\) → 123 的右邊,紅色;parent 123 與 uncle 345 都是紅 → 兩個塗黑、234 塗紅,234 是 root 再塗黑
→
(4) chained hashing
\(123\bmod11=2\),\(234\bmod11=3\),\(345\bmod11=4\),\(233\bmod11=2\)(與 123 同一格,新的接在最前面)
chaining 若接在串列尾端,index 2 的順序變成 123 → 233;兩種都被接受
(5) heap 取 min-heap(key 小的在上面)
插 123 → [123];插 234 → [123, 234];插 345 → [123, 234, 345]
插 233 放在 index 4,parent 是 index 2 的 234,\(233\lt234\) 交換;再比 index 1 的 123,\(123\lt233\) 停
heap 沒指定 min/max;若取 max-heap,結果為 [345, 233, 234, 123](插 234 與 123 交換、插 345 上到 root、插 233 與 123 交換)
見上列五張圖