21. Merge Two Sorted Lists

use std::borrow::Borrow;

/**
21. Merge Two Sorted Lists
https://leetcode.com/problems/merge-two-sorted-lists/

You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.

Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:
Input: list1 = [], list2 = []
Output: []

Example 3:
Input: list1 = [], list2 = [0]
Output: [0]

Constraints:
1. The number of nodes in both lists is in the range [0, 50].
2. -100 <= Node.val <= 100
3. Both list1 and list2 are sorted in non-decreasing order.
*/

// 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,
        }
    }
}

pub struct Solution {}

impl Solution {
    /*
    Solution: recurtion, like merge sort; Time:O(n), Space:O(n)
    */
    pub fn merge_two_lists(list1: Option<Box<ListNode>>, list2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        match (list1, list2) {
            (None, None) => None,
            (a, None) => a,
            (None, b) => b,
            //Some(listNode): get the value from list1 or list2 which is ref of ListNode
            (Some(mut listNode), Some(mut listNode2)) => {
                if (listNode.val < listNode2.val) {
                    listNode.next = Self::merge_two_lists(listNode.next,Some(listNode2));
                    return Some(listNode);
                } else {
                    listNode2.next = Self::merge_two_lists(Some(listNode),listNode2.next);
                    return Some(listNode2);
                }
            }
        }
    }
}

 

posted @ 2022-03-17 11:22  johnny_zhao  阅读(46)  评论(0编辑  收藏  举报