Merge Two Sorted Lists in Java: Dummy Node, Recursion, and the Collect-and-Sort Idea

  • Last Updated: November 26, 2026
  • By: javahandson
  • Series
img

Merge Two Sorted Lists in Java: Dummy Node, Recursion, and the Collect-and-Sort Idea

Learn to merge two sorted lists in Java with three approaches — collect-and-sort, recursion, and the iterative dummy node — each with a step-by-step dry run.

1. Introduction

Merge two sorted lists in Java is a classic linked list warm-up. It teaches a pattern you will reuse again and again. You get two linked lists that are already sorted. Your job is to join them into one list that stays sorted.

The task sounds small, yet it packs a nice lesson. Because both lists come pre-sorted, you can merge them by always picking the smaller head first. No extra sorting is needed once you spot that trick.

We build the answer in three steps, as always. The collect-and-sort idea is the easy first try. Recursion is the elegant next step. The iterative dummy node is the lean version interviewers love to see.

Every approach gets a full, step-by-step dry run on the same two lists. Nothing gets skipped, so you can watch each pointer move and see exactly how the merged list grows node by node.

2. Understanding the Problem

Let us pin down the rules before we touch any code.

  • You get two sorted linked lists, for example list1 = 1 → 3 → 5 → 7 → 9 → 11 → 13 and list2 = 2 → 4 → 6 → 8 → 10 → 12 → 14.
  • Both lists are sorted in increasing order already.
  • Return one linked list that holds all the nodes, still sorted in increasing order.
  • Either list can be empty. If one is empty, the answer is simply the other list.

For our pair the merged list runs 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10 → 11 → 12 → 13 → 14. Notice how the two lists interleave perfectly, which makes the dry runs easy to follow.

3. Concepts You Need Here

3.1 A Linked List Node Has a Value and a Next Pointer

A linked list is a chain of nodes. Every node stores a value and a pointer to the next node. The last node points to null, which marks the end.

  • The head is the first node of the list. From the head you can reach every other node.
  • Moving forward means following the next pointer, like node = node.next.

3.2 A Dummy Node Saves You From Special Cases

A dummy node is a throwaway node you place before the real head. It gives you a fixed starting point to attach nodes to. Later you just return dummy.next, which is the true head of the merged list.

  • Without a dummy, you must write extra code to handle the very first node.
  • With a dummy, the first node is attached the same way as every other node.

3.3 Merging Picks the Smaller Head Each Time

Since both lists are sorted, the smallest value overall is always at one of the two heads. So you compare the two heads, pick the smaller one, and move that list’s pointer forward. Repeat until one list runs out.

4. Approach 1: Collect Every Value, Then Sort

Walk both lists and dump every value into an array. Sort that array. Then build a brand new linked list from the sorted values. This idea ignores the fact that the lists are already sorted. So it does more work than needed, yet it is the simplest thing to reach for first.

4.1 Pseudocode

values = empty list

node = list1
while node is not null:
    values.add(node.value)
    node = node.next

node = list2
while node is not null:
    values.add(node.value)
    node = node.next

sort(values)

dummy = new node
tail = dummy
for v in values:
    tail.next = new node(v)
    tail = tail.next

return dummy.next

4.2 Pseudocode Explained

  • First we collect. We walk list1 and then list2, copying every value into one array.
  • Next we sort that array so all values line up in increasing order.
  • Then we rebuild. Starting from a dummy node, we create one new node per value and link them in a row.
  • Finally we return dummy.next, which skips the dummy and gives the real head of the merged list.

4.3 Java Code

import java.util.*;

public class MergeCollectSort {

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        List<Integer> values = new ArrayList<>();
        for (ListNode node = list1; node != null; node = node.next) {
            values.add(node.val);
        }
        for (ListNode node = list2; node != null; node = node.next) {
            values.add(node.val);
        }
        Collections.sort(values);

        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        for (int v : values) {
            tail.next = new ListNode(v);
            tail = tail.next;
        }
        return dummy.next;
    }
}

4.4 Java Code Explained

  • Line 6 makes an empty list to hold every value we find.
  • Lines 7 to 9 walk list1 one node at a time and copy each value in.
  • Then lines 10 to 12 do the same walk over list2.
  • Line 13 sorts all the collected values into increasing order.
  • Lines 15 and 16 set up a dummy node and a tail pointer that always points to the last attached node.
  • Lines 17 to 20 loop over the sorted values, build a fresh node for each, and hook it on at the tail.
  • Line 21 returns dummy.next, the head of the finished merged list.

4.5 Dry Run of the Collect-and-Sort Approach

We use list1 = 1 → 3 → 5 → 7 → 9 → 11 → 13 and list2 = 2 → 4 → 6 → 8 → 10 → 12 → 14. The collect pass walks list1 first, then list2, adding each value to the array in the order it is read.

Readingvalue readarray after this step
list1 node 11[1]
list1 node 23[1, 3]
list1 node 35[1, 3, 5]
list1 node 47[1, 3, 5, 7]
list1 node 59[1, 3, 5, 7, 9]
list1 node 611[1, 3, 5, 7, 9, 11]
list1 node 713[1, 3, 5, 7, 9, 11, 13]
list2 node 12[1, 3, 5, 7, 9, 11, 13, 2]
list2 node 24[1, 3, 5, 7, 9, 11, 13, 2, 4]
list2 node 36[1, 3, 5, 7, 9, 11, 13, 2, 4, 6]
list2 node 48[1, 3, 5, 7, 9, 11, 13, 2, 4, 6, 8]
list2 node 510[1, 3, 5, 7, 9, 11, 13, 2, 4, 6, 8, 10]
list2 node 612[1, 3, 5, 7, 9, 11, 13, 2, 4, 6, 8, 10, 12]
list2 node 714[1, 3, 5, 7, 9, 11, 13, 2, 4, 6, 8, 10, 12, 14]

After collecting, the array holds all of list1 followed by all of list2. Now Collections.sort rearranges it into increasing order.

Stagearray
Before sort[1, 3, 5, 7, 9, 11, 13, 2, 4, 6, 8, 10, 12, 14]
After sort[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

With the array sorted, the rebuild pass creates one node per value and links them in a row. The tail pointer always points to the last node added.

Stepvaluemerged list after attaching
111
221 → 2
331 → 2 → 3
441 → 2 → 3 → 4
551 → 2 → 3 → 4 → 5
661 → 2 → 3 → 4 → 5 → 6
771 → 2 → 3 → 4 → 5 → 6 → 7
881 → 2 → 3 → 4 → 5 → 6 → 7 → 8
991 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9
10101 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10
1111… → 10 → 11
1212… → 11 → 12
1313… → 12 → 13
1414… → 13 → 14 (complete)

The method returns dummy.next, so the final merged list is 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10 → 11 → 12 → 13 → 14.

4.6 Reading the Dry Run

Let us walk the three passes and see what each one does.

Collect pass over list1, then list2.

  • At node 1 of list1 the value 1 goes into the array, which now reads [1].
  • Moving node by node, the odd values 3, 5, 7, 9, 11, 13 get appended in that same order.
  • After list1 the array holds [1, 3, 5, 7, 9, 11, 13], which is list1 in its original order.
  • Then we switch to list2 and append 2, 4, 6, 8, 10, 12, 14 one at a time.

So the array ends up as list1 glued in front of list2. It is clearly out of order, because 13 sits right before 2. That is fine, because the sort step fixes it.

Sort pass.

Collections.sort takes the jumbled array and lines every value up from smallest to largest. The stray 2 that was stuck after 13 jumps forward to sit right after 1. After sorting, the array is a clean 1 through 14.

Rebuild pass.

  • We start with a dummy node and a tail that points at it.
  • For value 1 we make a new node, hook it onto the tail, and move the tail onto that new node.
  • Next, value 2 becomes a new node linked after 1, and the tail slides forward again.
  • Step by step, every sorted value turns into a node and joins the chain in order.

When the loop finishes, the chain runs 1 → 2 → … → 14. Returning dummy.next hands back the node holding 1, which is the real head.

💡 Interview Insight
A common follow-up is “does this use the sorted input?” Be honest: it throws the sorted order away and re-sorts, so it wastes the gift the problem gave you. Interviewers expect you to point this out yourself.

4.7 Time and Space Cost

  • Time is O(n log n), where n is the total number of nodes, because the sort dominates the work.
  • Space is O(n) for the array of values plus the brand new list of nodes we build.

This works, but it is heavier than it needs to be. Both lists arrive sorted already, so re-sorting is wasted effort. Next we use that sorted property directly.

5. Approach 2: Recursion

Compare the two heads. Pick the smaller one. Then say its next node is the merge of the rest. That one sentence is the whole recursion. The base case is simple: if either list is empty, return the other list as is.

5.1 Pseudocode

merge(a, b):
    if a is null:
        return b
    if b is null:
        return a

    if a.value <= b.value:
        a.next = merge(a.next, b)
        return a
    else:
        b.next = merge(a, b.next)
        return b

5.2 Pseudocode Explained

  • The two null checks are the base case. An empty list means there is nothing to merge, so the other list is the answer.
  • When a.value is smaller or equal, node a wins this round. Its next becomes the merge of everything after a with all of b.
  • Otherwise node b wins, and its next becomes the merge of all of a with everything after b.
  • Each call picks exactly one node, then trusts the recursive call to arrange the remaining nodes.

5.3 Java Code

public class MergeRecursive {

    public static ListNode mergeTwoLists(ListNode a, ListNode b) {
        if (a == null) {
            return b;
        }
        if (b == null) {
            return a;
        }
        if (a.val <= b.val) {
            a.next = mergeTwoLists(a.next, b);
            return a;
        } else {
            b.next = mergeTwoLists(a, b.next);
            return b;
        }
    }
}

5.4 Java Code Explained

  • Lines 4 to 6 handle an empty first list by returning the second list.
  • Then lines 7 to 9 handle an empty second list the same way.
  • Line 10 compares the two head values to decide which node comes next.
  • Lines 11 and 12 pick node a, set its next to the merge of the rest, and return a as this round’s head.
  • Lines 14 and 15 do the mirror case: pick node b and merge a with the rest of b.

5.5 Dry Run of the Recursion

We merge the same two lists. Each row is one call to mergeTwoLists. The indent shows how deep the call stack is. First the stack goes down, picking one node per call, until a list runs empty.

Call deptha headb headcomparepick → recurse on
0121 ≤ 2a=1 → merge(3…, 2…)
1323 > 2b=2 → merge(3…, 4…)
2343 ≤ 4a=3 → merge(5…, 4…)
3545 > 4b=4 → merge(5…, 6…)
4565 ≤ 6a=5 → merge(7…, 6…)
5767 > 6b=6 → merge(7…, 8…)
6787 ≤ 8a=7 → merge(9…, 8…)
7989 > 8b=8 → merge(9…, 10…)
89109 ≤ 10a=9 → merge(11…, 10…)
9111011 > 10b=10 → merge(11…, 12…)
10111211 ≤ 12a=11 → merge(13…, 12…)
11131213 > 12b=12 → merge(13…, 14…)
12131413 ≤ 14a=13 → merge(null, 14…)
13null14a is nullbase case → return 14

The deepest call hits the base case and returns the node 14. Now the stack unwinds. Each waiting call sets the next pointer of the node it picked, from the bottom back up to the top.

Unwind at depthnode that was pickedits next is set tochain built so far
12131413 → 14
11121312 → 13 → 14
10111211 → 12 → 13 → 14
9101110 → 11 → 12 → 13 → 14
89109 → 10 → 11 → 12 → 13 → 14
7898 → 9 → … → 14
6787 → 8 → … → 14
5676 → 7 → … → 14
4565 → 6 → … → 14
3454 → 5 → … → 14
2343 → 4 → … → 14
1232 → 3 → … → 14
0121 → 2 → … → 14 (final head)

When the top call returns, it hands back node 1, and the full list is 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10 → 11 → 12 → 13 → 14.

5.6 Reading the Dry Run

The recursion has two halves: the dive down and the climb back up. Let us read both.

The dive: picking one node per call.

  • At depth 0 the heads are 1 and 2. Since 1 ≤ 2, node 1 is picked, and we recurse on the rest of list1 with all of list2.
  • Dropping to depth 1, the heads are 3 and 2. Now 3 > 2, so node 2 wins and we recurse with 3 still waiting.
  • Going deeper, the heads keep alternating, because our lists interleave as odd then even. So the pick flips between list a and list b at almost every level.
  • By depth 12 the heads are 13 and 14. Here 13 ≤ 14, so 13 is picked, and list a runs empty.

At depth 13 the first list is null. The base case fires and returns node 14 untouched. That return value is the tail of our merged list.

The climb: wiring up the next pointers.

  • Unwinding at depth 12, the picked node 13 gets its next set to 14, giving 13 → 14.
  • Rising to depth 11, node 12 sets its next to 13, so the chain grows to 12 → 13 → 14.
  • Climbing higher, each node links to the result handed up from below, one pointer at a time.
  • Finally at depth 0, node 1 sets its next to 2, completing 1 → 2 → … → 14.

So the list is actually stitched together on the way back up. The picks happen going down, but the next pointers get wired going up. The top call then returns node 1 as the new head.

💡 Interview Insight
If asked “what is the catch with recursion here?”, mention the call stack. One level of recursion is used per node, so a very long list can overflow the stack. The iterative version coming next avoids that risk.

5.7 Time and Space Cost

  • Time is O(n), since each node is visited exactly once across all calls.
  • Space is O(n) for the recursion call stack, which grows one frame per node.

Recursion reads cleanly and uses the sorted order well. The one weak spot is that call stack. So next we do the same merge with a simple loop and only a few pointers.

6. Approach 3: Iterative Merge With a Dummy Node

Keep a dummy node and a tail pointer. Compare the two current heads, attach the smaller one to the tail, and move that pointer forward. Repeat until one list is empty, then attach whatever remains. This reuses the original nodes, so no new list is built. It is fast, lean, and the answer interviewers hope to see.

6.1 Pseudocode

dummy = new node
tail = dummy
lower = list1       // current head of list1
higher = list2      // current head of list2

while lower is not null and higher is not null:
    if lower.value <= higher.value:
        tail.next = lower
        lower = lower.next
    else:
        tail.next = higher
        higher = higher.next
    tail = tail.next

if lower is not null:
    tail.next = lower
else:
    tail.next = higher

return dummy.next

6.2 Pseudocode Explained

  • The dummy node gives the tail a fixed place to start, so the first real node is attached like any other.
  • Two pointers, lower and higher, track the current head of each list.
  • Inside the loop we compare the two heads and attach the smaller node to tail.next.
  • After attaching, we advance that list’s pointer and slide the tail onto the node we just added.
  • When the loop ends, one list is empty. The leftover of the other list is already sorted, so we attach it in one shot.
  • Returning dummy.next gives the head of the merged list.

6.3 Java Code

public class MergeIterative {

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        ListNode lower = list1;
        ListNode higher = list2;

        while (lower != null && higher != null) {
            if (lower.val <= higher.val) {
                tail.next = lower;
                lower = lower.next;
            } else {
                tail.next = higher;
                higher = higher.next;
            }
            tail = tail.next;
        }

        tail.next = (lower != null) ? lower : higher;
        return dummy.next;
    }
}

6.4 Java Code Explained

  • Lines 4 and 5 create the dummy node and point tail at it.
  • Lines 6 and 7 set lower and higher to the two list heads.
  • Line 9 keeps the loop running only while both lists still have nodes.
  • Lines 10 to 12 handle the case where lower wins: attach it, then move lower forward.
  • Lines 13 to 15 handle the mirror case where higher wins.
  • Then line 17 slides the tail onto whichever node was just attached.
  • Once the loop ends, line 20 attaches the non-empty leftover list in one step, since it is already sorted.
  • Finally, line 21 returns dummy.next, the head of the finished list.

6.5 Dry Run of the Iterative Approach

We merge list1 = 1 → 3 → 5 → 7 → 9 → 11 → 13 and list2 = 2 → 4 → 6 → 8 → 10 → 12 → 14. The legend: “lower head” is the current node of list1, “higher head” is the current node of list2. Each step attaches one node to the tail and advances one pointer.

steplower head (list1)higher head (list2)compareattachtail chain after step
1121 ≤ 2lower 11
2323 > 2higher 21 → 2
3343 ≤ 4lower 31 → 2 → 3
4545 > 4higher 41 → 2 → 3 → 4
5565 ≤ 6lower 51 → 2 → 3 → 4 → 5
6767 > 6higher 61 → 2 → 3 → 4 → 5 → 6
7787 ≤ 8lower 7… → 6 → 7
8989 > 8higher 8… → 7 → 8
99109 ≤ 10lower 9… → 8 → 9
10111011 > 10higher 10… → 9 → 10
11111211 ≤ 12lower 11… → 10 → 11
12131213 > 12higher 12… → 11 → 12
13131413 ≤ 14lower 13… → 12 → 13

After step 13, list1 is exhausted: lower is now null, while higher still points at node 14. So the loop stops.

Loop exit statevalue
lower (list1)null — list1 fully used
higher (list2)14 — one node left
attach leftovertail.next = higher, so 14 joins the end
final merged list1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10 → 11 → 12 → 13 → 14

6.6 Reading the Dry Run

Let us step through the loop and watch the two pointers march forward.

Step 1, heads 1 and 2.

  • The lower head is 1 and the higher head is 2.
  • Since 1 ≤ 2, node 1 is attached to the tail, and lower moves to 3.

The tail now sits on node 1, and the merged chain reads just 1.

Step 2, heads 3 and 2.

  • Now lower is 3 and higher is 2.
  • Because 3 > 2, node 2 wins, so higher moves to 4.

The chain grows to 1 → 2. Notice the pick flipped from list1 to list2.

Steps 3 to 6, the heads keep swapping.

  • At step 3 the heads are 3 and 4, so 3 is attached and lower moves to 5.
  • During step 4 the heads are 5 and 4, so 4 is attached and higher moves to 6.
  • Then step 5 attaches 5, and step 6 attaches 6, each time advancing the winner’s pointer.

Because our lists interleave as odd then even, the winner keeps alternating. So the merged chain climbs 1 → 2 → 3 → 4 → 5 → 6 in neat order.

Steps 7 to 13, climbing to the end.

  • The same compare-and-attach repeats for 7, 8, 9, 10, 11, 12, and 13.
  • By step 13 the heads are 13 and 14, so 13 is attached and lower moves to null.

With lower now null, list1 is fully used up. The loop condition fails, so we leave the loop.

Attaching the leftover.

  • At loop exit, lower is null but higher still points at node 14.
  • The line tail.next = higher hooks the entire remaining list2 on in one move.

Here that leftover is just node 14, but if list2 had several nodes left, they would all join at once because they are already sorted. Returning dummy.next gives the head node 1, and the full list is 1 → 2 → … → 14.

💡 Interview Insight
Interviewers often ask “why the dummy node?” Explain that it removes the special case for the first node. Without it, you would need an extra check to set the head separately, which clutters the loop.

6.7 Comparing the Three Traces

ApproachHow it mergesExtra memorySpeed feel
Collect and sortDump values, sort, rebuildNew array + new listSlowest of the three
RecursionPick smaller head, recurseCall stack, one frame per nodeFast, but stack-heavy
Iterative dummyLoop, attach smaller, reuse nodesA few pointers onlyFastest and leanest

7. Comparing the Three Approaches

All three return the same merged list. They just pay different prices to get there.

ApproachTimeSpaceNote
Collect and sortO(n log n)O(n)Simple, but re-sorts already sorted input
RecursionO(n)O(n)Elegant, but uses stack depth n
Iterative dummy nodeO(n)O(1)Fast and lean, the expected answer

The two linear approaches both visit each node once. What sets them apart is memory. Recursion needs a stack frame per node, while the iterative version uses only a handful of pointers, so it stays at O(1) extra space.

In an interview, mention collect-and-sort first to show you see the easy route. Then move to the iterative dummy node as your real answer. Keep recursion in your pocket as the clean, short alternative when stack depth is not a worry.

💡 Interview Insight
If pushed on the O(1) space claim for the iterative version, note that it reuses the original nodes instead of creating new ones. Only a fixed set of pointers is added, no matter how long the lists are.

8. Common Mistakes and Edge Cases

A few small traps catch beginners on this problem. Keep them in mind.

  • Forgetting the leftover attach drops the tail of the longer list, so the merged list ends too early.
  • Skipping the dummy node forces messy extra code just to set the first node of the result.
  • Moving a pointer before attaching its node loses that node from the final list.
  • Using < instead of <= still works for sorting, but it can flip the order of equal values, which matters when stability counts.
  • Both lists empty should return null, so make sure the dummy approach handles that cleanly.

Run the empty-list case and a single-node case through your code before you call it done. Those two catch more bugs than any long input will.

9. FAQ’s on merge two sorted lists in java

Q: What is the most efficient way to merge two sorted lists in Java?

A: The iterative dummy node approach is the most efficient. It runs in O(n) time and O(1) extra space because it reuses the original nodes instead of building a new list. You compare the two heads, attach the smaller node to the tail, and attach the leftover list at the end.

Q: Why do we use a dummy node when merging two sorted lists?

A: The dummy node gives the tail pointer a fixed starting point, so the first real node is attached the same way as every other node. Without it, you would need extra code just to set the head of the merged list, which clutters the loop.

Q: Should I use recursion or iteration to merge two sorted lists?

A: Both run in O(n) time. Recursion is clean and short but uses one stack frame per node, so a very long list can overflow the stack. Iteration with a dummy node uses only a few pointers and stays at O(1) extra space, so it is the safer pick for large inputs and the answer interviewers usually expect.

Q: What happens if one of the lists is empty?

A: If one list is empty, the merged result is simply the other list. The recursive version handles this with its base case, and the iterative version handles it with the final leftover-attach step, so no special head-setting code is needed.

Q: Why not just collect all values and sort them?

A: That works, but it wastes the fact that both lists already arrive sorted. Collecting and re-sorting costs O(n log n) time and O(n) extra space, while a direct merge is O(n). Mention it in an interview to show you see the easy route, then move to the dummy-node merge.

10. Conclusion

Merge two sorted lists in Java looks tiny, yet it teaches a habit you will reuse everywhere: when inputs arrive sorted, merge them instead of re-sorting. Once you see that, the problem almost solves itself.

Our seven-node lists showed the payoff clearly. Collect-and-sort worked but wasted the sorted order. Recursion used that order with a clean two-line idea. The iterative dummy node did the same merge with only a few pointers and no extra list.

So take the pattern, not just the answer. Reach for the dummy node to kill edge cases. Compare heads, attach the smaller, and remember to tack on the leftover at the end.

That merge habit shows up again in merge sort, in merging k lists, and in many range problems. It will serve you well on the harder problems waiting further down the list.

11. Further Reading

Leave a Comment