Algo-Sim › Linked Lists

Merge Two Sorted Lists

Easy · Linked Lists · step through it in Java, Python and C++ on your own input

Splice two sorted lists into one sorted list by relinking nodes behind a dummy head.

Problem

Given the heads of two linked lists, each sorted in non-decreasing order, splice their nodes together into one sorted list and return its head.

Constraints

Edge cases to test

Follow-up questions

Why a dummy head?
It removes the special case for the first node: always append to tail.next. O(m + n), O(1) extra.
How do you merge k lists?
A min-heap of list heads (O(N log k)) or pairwise merging in rounds (also O(N log k)).

Solution

Java

public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
    ListNode dummy = new ListNode(0), tail = dummy;
    while (list1 != null && list2 != null) {
        if (list1.val <= list2.val) {
            tail.next = list1;
            list1 = list1.next;
        } else {
            tail.next = list2;
            list2 = list2.next;
        }
        tail = tail.next;
    }
    tail.next = (list1 != null) ? list1 : list2;
    return dummy.next;
}

Python

def merge_two_lists(list1, list2):
    dummy = tail = ListNode()
    while list1 and list2:
        if list1.val <= list2.val:
            tail.next = list1
            list1 = list1.next
        else:
            tail.next = list2
            list2 = list2.next
        tail = tail.next
    tail.next = list1 if list1 else list2
    return dummy.next

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) {
        ListNode *dummy = new ListNode(0), *tail = dummy;
        while (list1 != nullptr && list2 != nullptr) {
            if (list1->val <= list2->val) {
                tail->next = list1;
                list1 = list1->next;
            } else {
                tail->next = list2;
                list2 = list2->next;
            }
            tail = tail->next;
        }
        tail->next = (list1 != nullptr) ? list1 : list2;
        return dummy->next;
    }
};

More Linked Lists problems