Start learning free

LESSON 156 OF 314 · LINKED LISTS

Merge Two Sorted Lists in Java: O(n + m) with a Dummy Node

Practice O(n + m) Read the full explanation

You get list1 and list2, the heads of two sorted linked lists.

Merge them into one sorted list, and return its head.

Use the nodes you already have. Change their next links to form one chain, and don't make new nodes.

Either list can be empty (its head is null). Both can be empty too.

 

Example 1:

Input: list1 = [2,6,7], list2 = [3,6,10,11]
Output: [2,3,6,6,7,10,11]
Explanation: Both lists have a 6.
The 6 from list1 goes first.
After the 7, list1 has no nodes left.
The rest of list2, 10 -> 11, goes at the end as it is.

Example 2:

Input: list1 = [5,9], list2 = []
Output: [5,9]
Explanation: The second list is empty.
So the answer is list1, unchanged.

Example 3:

Input: list1 = [-8,-1], list2 = [-5,4,4]
Output: [-8,-5,-1,4,4]
Explanation: Negative values and repeats work the same way.
The result is -8, -5, -1, then 4 -> 4.

 

Constraints:

  • Each list has 0 to 10,000 nodes.
  • Each value is from -100,000 to 100,000.
  • Both lists are in ascending order.
  • A value can repeat.

Note:

Your algorithm should run in O(n + m) time and use O(1) extra space, where n and m are the lengths of list1 and list2: it only re-links the nodes that are already there.

Start the merged list with a dummy node, an extra node before the first real node. Then the first node needs no special case. Every node is attached after the merged list's last node in the same way. The answer is the node after the dummy.

Merge the lists in a loop. A recursive merge goes one call deeper for every node. With 2 × 104 nodes, it can run out of call stack.

STEP 1 OF 11
    Ctrl + Enter to check

    JAVA · LINKED LISTS

    Merge Two Sorted Lists in Java, explained

    Problem overview

    The method mergeTwoLists receives list1 and list2, the heads of two singly linked lists that are each sorted in ascending order. It returns the head of one sorted list that contains every node of both. Either list can be empty, and an empty list is represented by null.

    The nodes must be spliced together, not copied: the result reuses the existing ListNode objects and only changes their next fields. The lesson provides the ListNode class, with an int val, a ListNode next and constructors that take nothing, a value, or a value and a next node.

    With list1 = 1->2->4 and list2 = 1->3->4 the method returns 1->1->2->3->4->4. With list1 = -4->10->12 and list2 = -7->0 it returns -7->-4->0->10->12, and with one empty list it returns the other list unchanged.

    Approach: always take the smaller front node

    Because both lists are sorted, the smallest value not yet placed is always one of the two front nodes. So the merge repeats one move: compare the fronts, attach the smaller node to the end of the merged list, and advance in the list it came from. This is the same merge step that merge sort uses.

    Each node is attached once, so the running time is O(n + m) for lists of n and m nodes. No node is created, so the extra space is O(1).

    The awkward part is the very first node. The merged list starts out empty, so the first attachment would need a special case: set the head instead of a next field. A dummy node removes it. It is a throwaway node placed in front of the real list, so the merged list is never empty, and every attachment looks the same: tail.next = something. The answer is dummy.next.

    A recursive version is shorter to write, but it goes one call deeper per node. With up to 10,000 nodes in each list, a loop is the safer choice.

    Step by step

    1. Create the dummy node with new ListNode() and keep it in dummy. Its value is never used.
    2. Declare tail and point it at dummy. It always stands on the last node of the merged list, which is where the next node is attached.
    3. Loop while both lists have nodes. Once one list is empty there is nothing left to compare.
    4. Compare the fronts with list1.val <= list2.val. Using <= means that on a tie the node from list1 goes first, so equal values keep their original order.
    5. Attach and advance. In the first branch, set tail.next = list1 and move list1 to list1.next. The else branch does the same with list2.
    6. Move tail forward once, after the if/else, since both branches attach a node at tail.next.
    7. Attach the rest in one go. After the loop, at least one list is used up. The other one is already sorted and every value in it is at least as large as what was merged, so tail.next can point at it directly. The conditional list1 != null ? list1 : list2 picks whichever list still has nodes. If both are used up, it picks list2, which is null, and that correctly ends the list.
    8. Return dummy.next, the first real node.

    The solution in Java

    class Solution {
        public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
            ListNode dummy = new ListNode();
            ListNode 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;
        }
    }
    

    Java details worth a look:

    • Variables hold references. tail.next = list1 makes tail.next refer to the same node object that list1 refers to. Nothing is copied. Then list1 = list1.next changes only the local variable list1, not the node.
    • The parameters are local. Reassigning list1 and list2 inside the method doesn't affect the caller's variables, though the nodes themselves are shared with the result.
    • Use != null and == for references. Comparing a reference with null is the one case where == is exactly what you want. Comparing the int values uses <= directly.
    • The conditional operator is an expression. condition ? a : b evaluates to a or b, so it can sit on the right side of an assignment.

    Complexity

    Time: O(n + m). Each loop turn attaches one node and moves one list forward, so the loop runs at most n + m times. Attaching the leftover list is one assignment.

    Space: O(1). The method creates one dummy node and uses two extra references. The merged list is built from the nodes already there.

    Edge cases and common mistakes

    • One or both lists empty. With list1 = null and list2 = 0, the loop never runs, tail.next becomes list2, and the result is 0. With both empty, dummy.next is still null.
    • Forgetting to move tail. Then every new node overwrites the same tail.next and the merged list loses nodes.
    • Returning dummy. The dummy node is not part of the answer, and its value is meaningless.
    • Looping until both lists are empty. Once one list is null, list1.val or list2.val throws a NullPointerException. The loop condition uses && for that reason.
    • Creating new nodes. It still produces a correct list but uses O(n + m) extra space, which breaks the lesson's constraint.

    Testing

    These results come from running the solution:

    • [1,2,4] and [1,3,4] give 1->1->2->3->4->4.
    • [] and [0] give 0.
    • [-4,10,12] and [-7,0] give -7->-4->0->10->12.
    • [] and [] give an empty list (null).
    • [1,5] and [2] give 1->2->5, and the first node returned is the same object as the head of the first list.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free