21. Merge Two Sorted Lists

Description of the Problem

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into 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:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

Solution 1 (Java and C++)

Tags: Sorting, LinkedList

Explantion

Since two lists are sorted. By comparing the smallest elements of each array, we know the smallest element of the merged list.

Code (Java)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummyHead = new ListNode(0);
        ListNode curr = dummyHead;
        while(list1 != null && list2 != null){
            if(list1.val < list2.val){
                curr.next = list1;
                list1 = list1.next;
            }
            else{
                curr.next = list2;
                list2 = list2.next;
            }
            curr = curr.next;
        }

         if(list1 != null){
             curr.next = list1;
         }else{
             curr.next = list2;
         }

        return dummyHead.next;
    }
}

Code (C++)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode * dummyHead = new ListNode();
        ListNode * curr = dummyHead;

        while (list1 != nullptr && list2 != nullptr){
            if(list1->val <= list2->val){
                curr->next = list1;
                list1 = list1->next;
            }
            else{
                curr->next = list2;
                list2 = list2->next;
            }
            curr = curr->next;
        }

        while (list1 != nullptr){
            curr->next = list1;
            list1 = list1->next;
            curr = curr->next;
        }

        while (list2 != nullptr){
            curr->next = list2;
            list2 = list2->next;
            curr = curr->next;
        }

        return dummyHead->next;

    }
};

Complexity

  • m and n are the number of elements of lists

Time complexity:

  • \( T(n) = O(m+n) \)

Auxiliary Space:

  • \( S(n) = O(1) \)
    • We added no extra node except the dummy head

Solution 2 - Rust

Tags: Rust LinkedList

Code (Rust)

// 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(list1: Option<Box<ListNode>>, list2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        let mut left_head = list1;
        let mut right_head = list2;
        let mut curr_head = None;

        while left_head.is_some() && right_head.is_some() {
            if let (Some(mut left_node), Some(mut right_node)) = (left_head.take(), right_head.take()){
                if left_node.val < right_node.val {
                    left_head = left_node.next.take();
                    right_head = Some(right_node);
                    if curr_head.is_some(){
                        left_node.next = curr_head;   
                    }
                    curr_head = Some(left_node);
                }else{
                    right_head = right_node.next.take();
                    left_head = Some(left_node);
                    if curr_head.is_some(){
                        right_node.next = curr_head;
                    }
                    curr_head = Some(right_node);
                }
                
            }
        }

        while let Some(mut left_node) = left_head.take(){
            left_head = left_node.next.take();
            if curr_head.is_some(){
                left_node.next = curr_head;
            }
            curr_head = Some(left_node);
        }

        while let Some(mut right_node) = right_head.take(){
            right_head = right_node.next.take();
            if curr_head.is_some(){
                right_node.next = curr_head;
            }
            curr_head = Some(right_node);
        }

        return Solution::reverse_list(curr_head);
    }

    #[inline(always)]
    fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>>{
        let mut curr = head;
        let mut prev = None;
        while let Some(mut node) = curr.take(){
            curr = node.next;
            node.next = prev;
            prev = Some(node);
        }

        return prev;
    }
}

Complexity

  • m and n are the number of elements of lists

Time complexity:

  • \( T(n) = O(m+n) \)

Auxiliary Space:

  • \( S(n) = O(1) \)
    • We added no extra node except the dummy head