File tree Expand file tree Collapse file tree 1 file changed +27
-8
lines changed Expand file tree Collapse file tree 1 file changed +27
-8
lines changed Original file line number Diff line number Diff line change 2
2
single linked list merge
3
3
This problem requires you to merge two ordered singly linked lists into one ordered singly linked list
4
4
*/
5
- // I AM NOT DONE
6
5
7
6
use std:: fmt:: { self , Display , Formatter } ;
8
7
use std:: ptr:: NonNull ;
9
- use std:: vec:: * ;
10
8
11
9
#[ derive( Debug ) ]
12
10
struct Node < T > {
@@ -66,13 +64,34 @@ impl<T> LinkedList<T> {
66
64
} ,
67
65
}
68
66
}
69
- pub fn merge ( list_a : LinkedList < T > , list_b : LinkedList < T > ) -> Self {
70
- //TODO
71
- Self {
72
- length : 0 ,
73
- start : None ,
74
- end : None ,
67
+ pub fn merge ( mut list_a : LinkedList < T > , mut list_b : LinkedList < T > ) -> Self
68
+ where
69
+ T : PartialOrd + Clone ,
70
+ {
71
+ let mut merged_list = LinkedList :: new ( ) ;
72
+
73
+ // 遍历两个链表,比较节点值
74
+ while let ( Some ( a) , Some ( b) ) = ( list_a. start , list_b. start ) {
75
+ if unsafe { a. as_ref ( ) . val . clone ( ) } <= unsafe { b. as_ref ( ) . val . clone ( ) } {
76
+ merged_list. add ( unsafe { a. as_ref ( ) . val . clone ( ) } ) ;
77
+ list_a. start = unsafe { a. as_ref ( ) . next } ;
78
+ } else {
79
+ merged_list. add ( unsafe { b. as_ref ( ) . val . clone ( ) } ) ;
80
+ list_b. start = unsafe { b. as_ref ( ) . next } ;
81
+ }
75
82
}
83
+
84
+ // 追加剩余节点
85
+ while let Some ( a) = list_a. start {
86
+ merged_list. add ( unsafe { a. as_ref ( ) . val . clone ( ) } ) ;
87
+ list_a. start = unsafe { a. as_ref ( ) . next } ;
88
+ }
89
+ while let Some ( b) = list_b. start {
90
+ merged_list. add ( unsafe { b. as_ref ( ) . val . clone ( ) } ) ;
91
+ list_b. start = unsafe { b. as_ref ( ) . next } ;
92
+ }
93
+
94
+ merged_list
76
95
}
77
96
}
78
97
You can’t perform that action at this time.
0 commit comments