• 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);
                    }
                }
            }
        }
    }
  • 相关阅读:
    Scrum Meeting Alpha
    Scrum Meeting Alpha
    Scrum Meeting Alpha
    你连自律都做不到,还奢谈什么自由?
    改变这个世界
    这世界没有人能随随便便成功
    “沙堆实验”
    解读那些年我们见过的“富人思维”
    心存希望,面朝大海
    闻香识女人 演讲台词
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/16016482.html
Copyright © 2020-2023  润新知