|
| 1 | +/** |
| 2 | + * [21] Merge Two Sorted Lists |
| 3 | + * |
| 4 | + * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. |
| 5 | + * |
| 6 | + * Example: |
| 7 | + * |
| 8 | + * Input: 1->2->4, 1->3->4 |
| 9 | + * Output: 1->1->2->3->4->4 |
| 10 | + * |
| 11 | + * |
| 12 | + */ |
| 13 | +pub struct Solution {} |
| 14 | + |
| 15 | +// submission codes start here |
| 16 | + |
| 17 | + // Definition for singly-linked list. |
| 18 | + #[derive(PartialEq, Eq, Debug)] |
| 19 | + pub struct ListNode { |
| 20 | + pub val: i32, |
| 21 | + pub next: Option<Box<ListNode>> |
| 22 | + } |
| 23 | + |
| 24 | + impl ListNode { |
| 25 | + #[inline] |
| 26 | + fn new(val: i32) -> Self { |
| 27 | + ListNode { |
| 28 | + next: None, |
| 29 | + val |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | +// recursive will be much easier to understand |
| 35 | +impl Solution { |
| 36 | + pub fn merge_two_lists(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { |
| 37 | + let mut dummy_head = Some(Box::new(ListNode{ |
| 38 | + val: 0, next: None, |
| 39 | + })); |
| 40 | + let mut head = &mut dummy_head; |
| 41 | + let (mut l1, mut l2) = (l1, l2); |
| 42 | + while l1.is_some() || l2.is_some() { |
| 43 | + if l1.is_none() { |
| 44 | + head.as_mut().unwrap().next = l2; break; |
| 45 | + } else if l2.is_none() { |
| 46 | + head.as_mut().unwrap().next = l1; break; |
| 47 | + } |
| 48 | + let next = if l1.as_ref().unwrap().val < l2.as_ref().unwrap().val { |
| 49 | + let (origin, next) = Solution::take_head(l1); |
| 50 | + l1 = origin; next |
| 51 | + } else { |
| 52 | + let (origin, next) = Solution::take_head(l2); |
| 53 | + l2 = origin; next |
| 54 | + }; |
| 55 | + head.as_mut().unwrap().next = next; |
| 56 | + head = &mut head.as_mut().unwrap().next; |
| 57 | + } |
| 58 | + dummy_head.unwrap().next |
| 59 | + } |
| 60 | + |
| 61 | + #[inline(always)] |
| 62 | + fn take_head(mut l: Option<Box<ListNode>>) -> (Option<Box<ListNode>>, Option<Box<ListNode>>) { |
| 63 | + let l_next = l.as_mut().unwrap().next.take(); |
| 64 | + let next = l.take(); |
| 65 | + l = l_next; |
| 66 | + (l, next) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +// helper function for test |
| 71 | +pub fn to_list(vec: Vec<i32>) -> Option<Box<ListNode>> { |
| 72 | + let mut current = None; |
| 73 | + for &v in vec.iter().rev() { |
| 74 | + let mut node = ListNode::new(v); |
| 75 | + node.next = current; |
| 76 | + current = Some(Box::new(node)); |
| 77 | + } |
| 78 | + current |
| 79 | +} |
| 80 | + |
| 81 | +// submission codes end |
| 82 | + |
| 83 | +#[cfg(test)] |
| 84 | +mod tests { |
| 85 | + use super::*; |
| 86 | + |
| 87 | + #[test] |
| 88 | + fn test_21() { |
| 89 | + assert_eq!(Solution::merge_two_lists(to_list(vec![1,2,4]), to_list(vec![1,3,4])), to_list(vec![1,1,2,3,4,4])); |
| 90 | + } |
| 91 | +} |
0 commit comments