Start learning free

LESSON 156 OF 314 · LINKED LISTS

Merge Two Sorted Lists in C++: Dummy Node and Two-Pointer Splice

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

    C++ · LINKED LISTS

    Merge Two Sorted Lists in C++, explained

    Problem overview

    The function 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. The head of an empty list is a null pointer, so either input, or both, can be empty.

    The lesson provides the node type, as a comment above the class: a ListNode with an int val, a ListNode *next and three constructors. The default constructor sets val to 0 and next to nullptr.

    With list1 = [1,2,4] and list2 = [1,3,4], the function returns [1,1,2,3,4,4]. With list1 = [-4,10,12] and list2 = [-7,0], the result is [-7,-4,0,10,12]. When one list is empty, the answer is the other list as it is.

    The statement asks for the nodes to be spliced together: the result is built by changing next pointers of the nodes that already exist, not by copying values into new nodes. It also sets a budget of O(n + m) time and O(1) extra space.

    Approach: always take the smaller front node

    Because both lists are sorted, the smallest value not yet used is always at the front of one of them. So the merge repeats one decision: compare the two front nodes, move the smaller one to the end of the merged list, and advance in the list it came from. Each node is moved once, which gives O(n + m) time. No new nodes are needed, so the extra space is constant.

    The awkward part is the very first node. The merged list is empty at the start, so there is no "last node" to attach to. The usual fix is a dummy node: a throwaway node placed in front of the merged list. Then the merged list is never empty, every node is attached to a last node in the same way, and the answer is whatever hangs after the dummy.

    A recursive merge is also possible ("the smaller head, followed by the merge of the rest"), but it goes one call deeper for each node. With up to 20,000 nodes in total, a loop is the safer choice.

    When the two front values are equal, the lesson takes the node from list1 first. The result is the same sorted sequence either way, but this rule keeps equal values in a predictable order: the ones from list1 come before the ones from list2.

    Step by step

    1. Create the dummy. new ListNode() allocates a node on the heap and returns a pointer to it, which goes into dummy. Its value doesn't matter.
    2. Create tail. It points at the last node of the merged list. For now the merged list is just the dummy, so tail starts there.
    3. Loop while both lists have nodes. A pointer is true when it isn't null, so list1 && list2 is the whole condition. Once either list runs out, there is nothing left to compare.
    4. Compare the front values with list1->val <= list2->val. The <= is what makes ties go to list1.
    5. Attach the chosen node: tail->next = list1. This links the node itself.
    6. Advance list1 to list1->next, because the node it pointed at now belongs to the merged list.
    7. Write the mirror image in the else branch for list2: attach it, then advance it.
    8. Move tail to tail->next, the node just attached. Both branches end the same way, so this line sits after the if/else.
    9. Attach the leftovers. After the loop, at least one list is empty. The other one is sorted and every value in it is at least as large as what was merged, so it can follow as it is. list1 ? list1 : list2 picks whichever is not null. If both are null, the merged list correctly ends with a null pointer.
    10. Return dummy->next, the first real node. The dummy is not part of the answer.

    The solution in C++

    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
            ListNode* dummy = new ListNode();
            ListNode* tail = dummy;
            while (list1 && 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 ? list1 : list2;
            return dummy->next;
        }
    };
    

    The C++ details worth a closer look:

    • Pointers in conditions. A null pointer converts to false and any other pointer to true, which is why while (list1 && list2) and list1 ? list1 : list2 work without comparing to nullptr.
    • -> against .. list1->val is shorthand for (*list1).val. Use -> on a pointer to a node.
    • The parameters are copies of the pointers. Assigning list1 = list1->next moves the local pointer only. The caller's variable still points at its original head, and the nodes themselves are shared, not copied.
    • The lists are changed. After the call, the nodes of both inputs are linked into one chain. The caller must use the returned head and stop using the old heads as separate lists: at most one of them is still the first node, and the other now sits somewhere inside the merged chain.
    • The dummy is never freed. new allocates one node that this code never deletes, so each call leaks a single node. A stack-allocated dummy, ListNode dummy; ListNode* tail = &dummy;, avoids that and returns dummy.next. The lesson's version is what its tests expect, and one small node per call is harmless there, but the stack form is the better habit.

    Complexity

    Time: O(n + m). Each turn of the loop attaches one node and advances at least one pointer, so the loop runs at most n + m times. Attaching the leftovers is one assignment, however long they are.

    Space: O(1). The only allocation is the dummy node, plus a few pointers. The merged list reuses the input nodes, and the loop has no recursion, so the call stack doesn't grow with the input.

    Edge cases and common mistakes

    • Both lists empty. The loop never runs, tail->next becomes nullptr and the function returns nullptr: an empty list.
    • One list empty. [] and [0] skip the loop and the leftover step attaches [0], so the result is [0].
    • One list much longer. In the example with [-4,10,12] and [-7,0], the loop stops after three comparisons and 10->12 is attached in one step.
    • Equal values. [1,1] merged with [1,1] gives four 1s. With <=, a front node of list1 that ties with one of list2 is taken first.
    • Forgetting to advance tail. The next node would overwrite tail->next, and the merged list would keep only the last attached node.
    • Forgetting the leftover step. The nodes left in the longer list would be lost.
    • Returning dummy. That would put a bogus extra node, with value 0, at the front of the answer.
    • Recursion on long lists. A recursive merge uses one stack frame per node, which can overflow the stack on inputs with tens of thousands of nodes.

    Testing

    • [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 [].
    • [5] and [] give [5].
    • [1,1] and [1,1] give [1,1,1,1].
    • Two lists of 20,000 nodes each (values 0 to 19999) give a list of 40,000 nodes, with no stack problems.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free