-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution2.rs
40 lines (40 loc) · 1.09 KB
/
Solution2.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn merge_two_lists(
mut list1: Option<Box<ListNode>>,
mut list2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
let mut new_list = ListNode::new(0);
let mut cur = &mut new_list;
while list1.is_some() && list2.is_some() {
let (l1, l2) = (list1.as_deref_mut().unwrap(), list2.as_deref_mut().unwrap());
if l1.val < l2.val {
let next = l1.next.take();
cur.next = list1.take();
list1 = next;
} else {
let next = l2.next.take();
cur.next = list2.take();
list2 = next;
}
cur = cur.next.as_deref_mut().unwrap();
}
cur.next = list1.or(list2);
new_list.next
}
}