-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#0021.merge-two-sorted-lists.rs
37 lines (36 loc) · 1.03 KB
/
#0021.merge-two-sorted-lists.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
// 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(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
match (l1, l2) {
(Some(node1), None) => Some(node1),
(None, Some(node2)) => Some(node2),
(Some(mut node1), Some(mut node2)) => {
if node1.val < node2.val {
let n = node1.next.take();
node1.next = Solution::merge_two_lists(n, Some(node2));
Some(node1)
} else {
let n = node2.next.take();
node2.next = Solution::merge_two_lists(Some(node1), n);
Some(node2)
}
},
_ => None,
}
}
}