22 single linked list merge
33 This problem requires you to merge two ordered singly linked lists into one ordered singly linked list
44*/
5- // I AM NOT DONE
5+ //
66
77use std:: fmt:: { self , Display , Formatter } ;
88use std:: ptr:: NonNull ;
@@ -47,7 +47,7 @@ impl<T> LinkedList<T> {
4747 pub fn add ( & mut self , obj : T ) {
4848 let mut node = Box :: new ( Node :: new ( obj) ) ;
4949 node. next = None ;
50- let node_ptr = Some ( unsafe { NonNull :: new_unchecked ( Box :: into_raw ( node) ) } ) ;
50+ let node_ptr = NonNull :: new ( Box :: into_raw ( node) ) ;
5151 match self . end {
5252 None => self . start = node_ptr,
5353 Some ( end_ptr) => unsafe { ( * end_ptr. as_ptr ( ) ) . next = node_ptr } ,
@@ -70,13 +70,57 @@ impl<T> LinkedList<T> {
7070 }
7171 }
7272 pub fn merge ( list_a : LinkedList < T > , list_b : LinkedList < T > ) -> Self
73- {
73+
7474 //TODO
75- Self {
76- length : 0 ,
77- start : None ,
78- end : None ,
79- }
75+ where
76+ T : Ord +Clone , // 要求 T 实现 Ord 特质,支持比较大小
77+ {
78+ let mut merged_list = LinkedList :: new ( ) ;
79+ // 初始化两个指针,指向两个链表的头节点
80+ let mut ptr_a = list_a. start ;
81+ let mut ptr_b = list_b. start ;
82+
83+ // 双指针循环比较,直到其中一个链表遍历完毕
84+ while let ( Some ( a) , Some ( b) ) = ( ptr_a, ptr_b) {
85+ let a_node = unsafe { a. as_ref ( ) } ;
86+ let b_node = unsafe { b. as_ref ( ) } ;
87+
88+ // 比较节点值,将较小的节点添加到新链表
89+ if a_node. val <= b_node. val {
90+ // 取出 ptr_a 指向的节点,添加到新链表
91+ merged_list. add ( a_node. val . clone ( ) ) ; // 注意:需要 T 实现 Clone(下方补充约束)
92+ // 移动 ptr_a 到下一个节点
93+ ptr_a = a_node. next ;
94+ } else {
95+ // 取出 ptr_b 指向的节点,添加到新链表
96+ merged_list. add ( b_node. val . clone ( ) ) ;
97+ // 移动 ptr_b 到下一个节点
98+ ptr_b = b_node. next ;
99+ }
100+ }
101+
102+ // 处理 list_a 剩余的节点
103+ while let Some ( a) = ptr_a {
104+ let a_node = unsafe { a. as_ref ( ) } ;
105+ merged_list. add ( a_node. val . clone ( ) ) ;
106+ ptr_a = a_node. next ;
107+ }
108+
109+ // 处理 list_b 剩余的节点
110+ while let Some ( b) = ptr_b {
111+ let b_node = unsafe { b. as_ref ( ) } ;
112+ merged_list. add ( b_node. val . clone ( ) ) ;
113+ ptr_b = b_node. next ;
114+ }
115+
116+ merged_list
117+
118+
119+ // Self {
120+ // length: 0,
121+ // start: None,
122+ // end: None,
123+ // }
80124 }
81125}
82126
@@ -104,6 +148,9 @@ where
104148 }
105149}
106150
151+ // 为了支持 val.clone(),需要为 LinkedList<T> 的方法补充 Clone 约束
152+ impl < T : Clone + Ord > LinkedList < T > { }
153+
107154#[ cfg( test) ]
108155mod tests {
109156 use super :: LinkedList ;
0 commit comments