Skip to content

Commit cb198f5

Browse files
04121424
1 parent fb872b2 commit cb198f5

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

exercises/algorithm/algorithm1.rs

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,9 @@
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
65

76
use std::fmt::{self, Display, Formatter};
87
use std::ptr::NonNull;
9-
use std::vec::*;
108

119
#[derive(Debug)]
1210
struct Node<T> {
@@ -66,13 +64,34 @@ impl<T> LinkedList<T> {
6664
},
6765
}
6866
}
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+
}
7582
}
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
7695
}
7796
}
7897

0 commit comments

Comments
 (0)