Skip to content

Commit 1493a69

Browse files
committed
merge-two-sorted-lists
1 parent 4d3d624 commit 1493a69

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

merge-two-sorted-lists/DaleSeo.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// TC: O(m + n)
2+
// SC: O(1)
3+
impl Solution {
4+
pub fn merge_two_lists(list1: Option<Box<ListNode>>, list2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
5+
let mut dummy = Box::new(ListNode::new(-1));
6+
let mut node = &mut dummy;
7+
let (mut l1, mut l2) = (list1, list2);
8+
while l1.is_some() && l2.is_some() {
9+
let val1 = l1.as_ref().unwrap().val;
10+
let val2 = l2.as_ref().unwrap().val;
11+
if val1 < val2 {
12+
node.next = l1;
13+
node = node.next.as_mut().unwrap();
14+
l1 = node.next.take();
15+
} else {
16+
node.next = l2;
17+
node = node.next.as_mut().unwrap();
18+
l2 = node.next.take();
19+
}
20+
}
21+
node.next = l1.or(l2);
22+
dummy.next
23+
}
24+
}

0 commit comments

Comments
 (0)