Start learning free

LESSON 156 OF 314 · LINKED LISTS

Merge Two Sorted Lists in C#: Dummy Node and a Tail Pointer

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 method MergeTwoLists receives list1 and list2, the heads of two singly linked lists whose values are in ascending order. It returns the head of one sorted list that contains all the nodes of both. The nodes are re-linked, not copied: no new nodes are created for the result. Either list can be empty, and an empty list is represented by null.

    The lesson provides the ListNode class, with an int val field, a ListNode next field and constructors that set them. You only write the method.

    For [1,2,4] and [1,3,4] the result is [1,1,2,3,4,4]. For [] and [0] it is [0], and for [-4,10,12] and [-7,0] it is [-7,-4,0,10,12]. The target is O(n + m) time and O(1) extra space, where n and m are the two lengths.

    Approach: always take the smaller front node

    Both lists are already sorted, so the smallest value not yet used is always at the front of one of them. Compare the two front nodes, move the smaller one to the end of the merged list, and repeat. Each node is moved once, which gives O(n + m) time. Because nodes are re-linked rather than copied, the extra memory is a few references.

    The awkward part is the very first node. The merged list is empty at the start, so "attach after the last node" has no last node. You could special-case the first attachment, but a cleaner trick is a dummy node: an extra node placed in front of the merged list. It makes the merged list non-empty from the start, so every real node is attached the same way, after a tail reference that points at the current last node. At the end the answer is dummy.next, and the dummy itself is thrown away.

    When one list runs out, you don't need to compare anymore. The rest of the other list is sorted and none of its values is smaller than what is already merged, so the whole remainder can be attached in one assignment.

    Step by step

    1. Create the dummy node with new ListNode(). Its val is never used.
    2. Point tail at the dummy. Right now the merged list is only the dummy, so the dummy is also its last node.
    3. Loop while both lists have nodes. The condition is list1 != null && list2 != null. Once either is null, there is nothing left to choose between.
    4. Compare the front values with list1.val <= list2.val. Using <= sends equal values to list1 first, so the merge is stable: among equal values, list1's nodes come before list2's.
    5. Attach and advance in the first branch: set tail.next = list1, then list1 = list1.next. The node you just attached is now part of the merged list, so what remains of list1 starts after it.
    6. Do the mirror image in the else branch for list2.
    7. Move tail forward with tail = tail.next, after the if/else. Both branches attach a node at tail.next, so this line is shared.
    8. Attach the leftover after the loop with the conditional operator: list1 != null ? list1 : list2. If both are used up, this is null, which correctly ends the list.
    9. Return dummy.next, the first real node. If both inputs were empty it is null, an empty list.

    The solution in C#

    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;
        }
    }
    

    The C# details worth knowing:

    • ListNode is a class, so variables hold references. tail.next = list1 makes the merged list point at the very same node object, not a copy. That is why no extra memory is needed, and also why the input lists are damaged: after the merge, the original list1 and list2 heads are part of the merged list, and their next fields have been rewritten.
    • list1 and list2 are ordinary local variables. Assigning list1 = list1.next moves the local reference only. The caller's variable still points at the old head.
    • Comparing with null uses == and !=. For a class like ListNode, which doesn't overload them, they compare references, and null means "no node".
    • The conditional operator needs both branches to be one type. Here both are ListNode, so cond ? list1 : list2 is fine, and the result can be assigned straight to tail.next.
    • The dummy's fields are default values. new ListNode() leaves val at 0 and next at null. The value doesn't matter, because the dummy is never compared and is not part of the answer.

    Complexity

    Time: O(n + m). Each loop turn attaches one node and advances one of the two lists, so the loop runs at most n + m times. The leftover is attached with a single assignment, no matter how long it is.

    Space: O(1). The method uses three references, dummy, tail and the two parameters, whatever the input size. A recursive version that merges the rest of the lists after choosing one node would use a call-stack frame per node, and lists of up to 20,000 nodes in total can overflow the stack. The loop avoids that.

    Edge cases and common mistakes

    • Both lists empty. The loop doesn't run, tail.next becomes null, and dummy.next is null.
    • One list empty. The loop doesn't run, and the other list is attached whole.
    • Equal values. With <=, the node from list1 goes first. With two single nodes of value 7, the returned head is list1's node and its next is list2's node. Using < would still give a sorted result but would swap which node comes first.
    • Forgetting to advance tail. Every new node would overwrite tail.next, and the merged list would end up with only the last attached node and the leftover.
    • Forgetting the leftover. If one list is longer, its remaining nodes would be dropped from the result.
    • Returning dummy instead of dummy.next. The result would start with an extra node holding 0.
    • Not moving list1 or list2. The same node would be compared and attached over and over, which makes the loop endless.

    Testing

    Each pair below was run through the method, and the merged lists print as shown.

    • [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 [], and the returned head is null.
    • [5] and [] give [5].
    • [2,2] and [2] give [2,2,2].
    • Two lists of 10,000 nodes each, one holding the even numbers and the other the odd numbers, merge into 20,000 nodes without a stack problem.
    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