|  | 
|  | 1 | +// 21. Merge Two Sorted Lists | 
|  | 2 | +// https://leetcode.com/problems/merge-two-sorted-lists/description/ | 
|  | 3 | +// Topics: Linked List. | 
|  | 4 | +// Difficulty: Easy. | 
|  | 5 | + | 
|  | 6 | +#[test] | 
|  | 7 | +fn test_21_merge_two_sorted_lists() {} | 
|  | 8 | + | 
|  | 9 | +#[derive(Debug)] | 
|  | 10 | +pub struct Solution; | 
|  | 11 | + | 
|  | 12 | +// --------------------------------- | 
|  | 13 | +// copy to leetcode starts from here | 
|  | 14 | +// --------------------------------- | 
|  | 15 | + | 
|  | 16 | +// Definition for singly-linked list. | 
|  | 17 | +#[derive(PartialEq, Eq, Clone, Debug)] | 
|  | 18 | +pub struct ListNode { | 
|  | 19 | +    pub val: i32, | 
|  | 20 | +    pub next: Option<Box<ListNode>>, | 
|  | 21 | +} | 
|  | 22 | + | 
|  | 23 | +// impl ListNode { | 
|  | 24 | +//     #[inline] | 
|  | 25 | +//     fn new(val: i32) -> Self { | 
|  | 26 | +//         ListNode { next: None, val } | 
|  | 27 | +//     } | 
|  | 28 | +// } | 
|  | 29 | + | 
|  | 30 | +impl Solution { | 
|  | 31 | +    pub fn merge_two_lists( | 
|  | 32 | +        list1: Option<Box<ListNode>>, | 
|  | 33 | +        list2: Option<Box<ListNode>>, | 
|  | 34 | +    ) -> Option<Box<ListNode>> { | 
|  | 35 | +        match (list1, list2) { | 
|  | 36 | +            (None, None) => None, | 
|  | 37 | +            (Some(n), None) | (None, Some(n)) => Some(n), | 
|  | 38 | +            (Some(l1), Some(l2)) => { | 
|  | 39 | +                if l1.val >= l2.val { | 
|  | 40 | +                    Some(Box::new(ListNode { | 
|  | 41 | +                        val: l2.val, | 
|  | 42 | +                        next: Solution::merge_two_lists(Some(l1), l2.next), | 
|  | 43 | +                    })) | 
|  | 44 | +                } else { | 
|  | 45 | +                    Some(Box::new(ListNode { | 
|  | 46 | +                        val: l1.val, | 
|  | 47 | +                        next: Solution::merge_two_lists(l1.next, Some(l2)), | 
|  | 48 | +                    })) | 
|  | 49 | +                } | 
|  | 50 | +            } | 
|  | 51 | +        } | 
|  | 52 | +    } | 
|  | 53 | +} | 
0 commit comments