Scrivio Interview library
Linked listsLinked listsReported 59 times · 16 min read · updated 15 November 2026

Merge two sorted linked lists into one sorted linked list.

1What it means to merge two sorted lists

Imagine two lines of children, each arranged from shortest to tallest, waiting at one door into a hall where they must form a single line, again from shortest to tallest. The teacher at the door need not measure everyone. She looks only at the two children at the front of the lines, sends the shorter one through, and repeats. The shortest child left is always at the front of one of the two lines, because each line is already in order.

Our question is that scene with linked lists. A linked list is a chain of nodes, where each node holds a value and a reference called next, a variable that names the node after it. The first node is the head, and the last node's next is null, meaning nothing. We are given the heads of two lists, each sorted from smallest to largest, and we must return the head of one list that holds all their nodes in sorted order.

Let us keep one example for the whole article. List a is 2 -> 5 -> 9 and list b is 1 -> 5 -> 6 -> 12. The answer is 1 -> 2 -> 5 -> 5 -> 6 -> 9 -> 12, seven nodes, because a has three nodes and b has four.

Do it once on paper, like the teacher. The fronts are 2 and 1, so 1 goes first. Then 2 and 5, so 2. Then 5 and 5, a tie, so take either; we will take the one from a. Then 9 and 5, so 5. Then 9 and 6, so 6. Then 9 and 12, so 9. Now list a is empty, and the rest of b, just 12, goes on the end. That is the whole algorithm, done with children instead of arrows.

PictureThe two sorted lists and the merged list we want

Top row: list a. Middle row: list b. Bottom row: the merged list, made of the same seven nodes.

  1. 259a15612b12556912

    1List a is 2 5 9 and list b is 1 5 6 12. The merged list must hold all seven nodes in order: 1 2 5 5 6 9 12.

What to assume

Should we create new nodes or reuse the ones we are given?
We reuse them, by changing their next references; this is called splicing, and it saves memory.
Can either list be empty?
Yes, and then the answer is simply the other list.
Can values repeat, inside a list or across the two?
Yes, and every copy stays in the result.
Do we need to keep the original lists intact?
No, their nodes become the merged list.

A careful candidate asks a few questions first. Should we create new nodes or reuse the ones we are given? We reuse them, by changing their next references; this is called splicing, and it saves memory. Can either list be empty? Yes, and then the answer is simply the other list. Can values repeat, inside a list or across the two? Yes, and every copy stays in the result. Do we need to keep the original lists intact? No, their nodes become the merged list.

2How to recognise a merge of sorted sequences

Meeting this question first, many people think of the result as something brand new, so they reach for a fresh list or an array they can sort. That gives correct code, but the question hands us two lists that are already sorted, and that word deserves attention. Let us read the clues one at a time.

The first clue is the word sorted, said of both inputs. In a sorted list the smallest value is at the head. So the smallest value of the two lists together must be one of the two heads, and finding it costs a single comparison. That is what the teacher at the door relied on.

The second clue is linked lists. We cannot jump to the middle of a linked list, but we can do something an array cannot: move a node from one list to another by changing one next reference, without copying anything. So building the result means unhooking nodes from the inputs and hanging them on the end of the result.

The third clue is one sorted linked list as the output. The result grows only at its end, one node at a time, so we need to keep a finger on its last node, which we will call tail. Hanging a node on the end is then just tail.next = node.

Together these clues point to the linked lists family of patterns and to the technique called merging, the same step that merge sort uses to combine two sorted halves. It is a two-pointer method: one pointer, a reference that names a node, walks list a, and another walks list b, and at each step the pointer on the smaller value moves forward. The general rule to carry to new problems is that two sorted inputs and one sorted output almost always mean a merge, comparing only the fronts.

A few other tools look relevant but do more than is needed. Sorting everything again ignores the order we were given. A heap, a structure that always hands back its smallest element, is the right tool for merging k lists, but with two fronts one comparison is enough. Fast and slow pointers, which walk one list at two speeds, answer other questions, such as finding the middle.

3The honest first attempt, collecting and sorting

The brute force is to forget that the inputs are sorted and turn the problem into one we already know how to solve. Copy every value from both lists into an ArrayList, sort it with the library, and build a new linked list from the sorted values. It is short and correct, and there is no shame in starting from it.

Java
static Node mergeBySort(Node a, Node b) {
List<Integer> values = new ArrayList<>();
for (Node n = a; n != null; n = n.next) values.add(n.val); // copy list a
for (Node n = b; n != null; n = n.next) values.add(n.val); // copy list b
Collections.sort(values); // sort all of it again
Node dummy = new Node(0), tail = dummy;
for (int v : values) { tail.next = new Node(v); tail = tail.next; } // build new nodes
return dummy.next;
}

Let us do it by hand. The two walks copy [2, 5, 9, 1, 5, 6, 12], seven values. Sorting gives [1, 2, 5, 5, 6, 9, 12]. The last loop builds seven brand new nodes holding those values, hung behind a dummy node, and returns the node after the dummy.

Now let us count. Copying visits seven nodes, a good sort of seven values makes around twenty comparisons, and the rebuild makes seven new nodes. For lists of n and m nodes, the sort dominates, so the time is O((n + m) log(n + m)), read as order n plus m times its logarithm. The extra memory, called the space, is O(n + m), for the copied values and the new nodes.

Where is the waste? The sort spends most of its effort discovering an order that was already there. Within list a, 2 already comes before 5 and 5 before 9, and the sort works that out again. It also throws away the nodes we were given, which can surprise other code holding a reference to one of them.

So let us ask the question that leads further. When we stood at the two heads, 2 and 1, did we already know which value came first in the answer? We did, after one comparison. The sort ignored that knowledge.

4Getting to the splicing loop, one observation at a time

The first observation is the one from the door. The smallest node of all is at the front of a or at the front of b, so one comparison, a.val <= b.val, finds it. We unhook that node by moving its list's pointer on, a = a.next or b = b.next, and the node is ready to be hung on the result.

The second observation is that after taking one node, the situation is exactly the same as before, only smaller. Both lists are still sorted, so the smallest remaining node is again at one of the two fronts. That means one loop, repeated while both lists still have nodes, does all the comparing.

Now the question every beginner asks. Where do we hang the very first node, when the result is empty and there is no tail? A special case would work, making that node the head, but special cases breed bugs. Instead we make one extra node, called the dummy, before the loop. It holds no real value and is never returned. tail starts on the dummy, so even the first real node is hung with tail.next = node, the same line as every other node. At the end the real head is dummy.next.

The third observation is about the end. When one list runs out, the loop stops, but the other may still have nodes. Must we move them one by one? No. The leftover nodes are already linked to each other in sorted order, and every one of them is at least as large as everything already in the result. So a single assignment, tail.next = the leftover list, attaches all of them at once. In our example, after 9 is taken, list a is empty and one link attaches 12.

One detail puzzles people who print the list halfway. When node 1 is hung after the dummy, its next still points to node 5 of list b. That is harmless, because the next step overwrites tail.next, and the final line sets the last link.

Why is this correct? At the top of every step the result holds the smallest nodes taken so far, in sorted order, and every node still in a or b is at least as large as the result's last node. Taking the smaller front keeps both facts true, because that node is no larger than anything left in either list. When one list is empty, the other list's nodes are all at least as large as the result's last node and are already in order, so attaching them finishes a sorted list containing every node.

The most common mistake is to forget that final attachment. The loop alone stops as soon as one list runs out, and without the last line our example would lose node 12. The second most common is returning dummy instead of dummy.next, which puts a stray 0 at the front of the answer.

5Watching the two lists merge

The picture plays the loop on our example. The top row is list a and the middle row is list b. The bottom row is the result, starting with the dummy node D. A faded node in the top two rows has already been moved into the result; it is the same node, drawn again in its new place. The two marked fronts are the values being compared, and tail stands on the result's last node.

Watch two things. First, only the two fronts are ever compared. Second, the last step attaches node 12 without any comparison at all.

Step throughMerging 2 5 9 with 1 5 6 12

Faded nodes in the top two rows have moved into the result. D is the dummy node, which is never returned.

  1. 259a15612bDtail
    a
    2
    b
    1
    result
    empty

    1We start with a on node 2 and b on node 1. The result is only the dummy node D, a placeholder, and tail stands on it.

  2. 259a15612bD1tail
    a
    2
    b
    5
    result
    1

    2The fronts are 2 and 1. Since 1 is smaller, node 1 is hung after tail, b moves on to node 5, and tail moves onto node 1.

  3. 259a15612bD12tail
    a
    5
    b
    5
    result
    1 2

    3The fronts are 2 and 5. Since 2 is smaller, node 2 is hung after node 1, and a moves on to its second node, 5.

  4. 259a15612bD125tail
    a
    9
    b
    5
    result
    1 2 5

    4The fronts are 5 and 5, a tie. Because the test is a.val <= b.val, the 5 from list a goes first, and a moves on to 9.

  5. 259a15612bD1255tail
    a
    9
    b
    6
    result
    1 2 5 5

    5The fronts are 9 and 5. Since 5 is smaller, the 5 from list b is hung on, and b moves on to node 6.

  6. 259a15612bD12556tail
    a
    9
    b
    12
    result
    1 2 5 5 6

    6The fronts are 9 and 6. Since 6 is smaller, node 6 is hung on, and b moves on to node 12.

  7. 25915612bD125569tail
    a
    null
    b
    12
    result
    1 2 5 5 6 9

    7The fronts are 9 and 12. Since 9 is smaller, node 9 is hung on. List a is now used up, so a is null and the loop stops.

  8. 25915612bD12556912tail
    a
    null
    b
    12
    result
    1 2 5 5 6 9 12

    8Only list b is left, holding node 12, and it is sorted and larger than everything taken. One link, tail.next = b, attaches it.

  9. 25915612D12556912head
    returned
    dummy.next
    result
    1 2 5 5 6 9 12

    9We return dummy.next, which is node 1. The merged list is 1 2 5 5 6 9 12, built from the original seven nodes.

Let us read a few frames back. In the second frame the fronts are 2 and 1, the smaller is node 1 from b, and it moves to the result. The fourth frame is the tie: both fronts are 5, and because the test is a.val <= b.val, the node from list a is taken first. Taking ties from the first list keeps equal values in the order they came.

In the seventh frame node 9 is taken, list a becomes empty, and the loop stops after six comparisons. The eighth frame is the single link that attaches node 12. Count the work: six comparisons and seven links for seven nodes, against about twenty comparisons and seven new nodes for the sort.

6The Java solution, read line by line

Here is the complete program, with a small Node class, the merge method, and two helpers: build makes a list from values and show prints one. main merges our example, a pair where one list ends long before the other, and two cases with empty lists. Each comment shows what that line prints.

Java
public class MergeLists {
static class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
// Splices the nodes of two sorted lists into one sorted list; no new nodes are created.
static Node merge(Node a, Node b) {
Node dummy = new Node(0); // a placeholder in front of the result
Node tail = dummy; // the last node of the result so far
while (a != null && b != null) {
if (a.val <= b.val) { // <= keeps equal values in their original order
tail.next = a;
a = a.next;
} else {
tail.next = b;
b = b.next;
}
tail = tail.next;
}
tail.next = (a != null) ? a : b; // one list is used up: attach the rest of the other
return dummy.next;
}
static Node build(int... values) {
Node dummy = new Node(0), tail = dummy;
for (int v : values) { tail.next = new Node(v); tail = tail.next; }
return dummy.next;
}
static String show(Node head) {
StringBuilder sb = new StringBuilder("[");
for (Node n = head; n != null; n = n.next) sb.append(n.val).append(n.next != null ? " " : "");
return sb.append("]").toString();
}
public static void main(String[] args) {
System.out.println(show(merge(build(2, 5, 9), build(1, 5, 6, 12)))); // [1 2 5 5 6 9 12]
System.out.println(show(merge(build(5, 6), build(1, 2, 3)))); // [1 2 3 5 6]
System.out.println(show(merge(build(), build(0)))); // [0]
System.out.println(show(merge(build(), build()))); // []
}
}

Let us read merge in the order it runs. First we create the dummy node and set tail to it, so the result has a last node from the very start. The while loop runs only while both a and b still have nodes, because a comparison needs two fronts.

Inside the loop, if a.val <= b.val, we hang node a after tail with tail.next = a, and then step a onto the rest of its list with a = a.next. Otherwise we do the same with b. The order of those two lines matters: we must hang the node before moving a, or we would lose our only reference to it. After either branch, tail = tail.next moves tail onto the node we just hung, so the next node goes after it.

When the loop ends, at least one list is empty. The line tail.next = (a != null) ? a : b attaches whichever list still has nodes. If both are empty, it attaches null, which correctly ends the result. Finally we return dummy.next, the first real node, skipping the placeholder.

The helpers build and show only make the program runnable. Notice that merge never calls new Node except for the dummy, so the result is made entirely of the nodes we were given.

7How much it costs, and the cases at the edges

Let us count on the example first. The loop ran six times, one comparison and two reference moves each, and then one final link attached the last node. In general each step of the loop places one node, so it runs at most n + m - 1 times for lists of n and m nodes, and the final link is one more step. So the time is O(n + m), which is the best possible, since every node must be placed.

The extra space is O(1). Besides the one dummy node, the method keeps only three references, a, b and tail, however long the lists are. The sort-based method needed O(n + m) for its copies, and a recursive version needs one waiting call per node.

Comparing the ways to merge
ApproachTimeExtra spaceReuses the nodes?
Collect, sort, rebuild (brute force)O((n + m) log(n + m))O(n + m)no
Recursive mergeO(n + m)O(n + m) call stackyes
Loop with a dummy head and tailO(n + m)O(1)yes

The edge cases need no special code. If either list is empty, the loop never runs and the last line attaches the other list whole, so merging an empty list with [0] gives [0], and two empty lists give []. If every value of one list is smaller than the other's first, as with [5 6] and [1 2 3], the loop takes the whole smaller list and the last line attaches the other, giving [1 2 3 5 6].

Repeated values are kept, each placed exactly once, with ties from list a first. And because the loop only changes next references, it never runs out of stack, however long the lists are.

8Follow-up questions

How would you merge k sorted lists instead of two?

With k lists there are k fronts, and comparing them all would cost k comparisons per node. A min-heap, which hands back its smallest element in O(log k) time, removes that cost. We put the head of each list in the heap, then repeatedly take the smallest node out, hang it on the result behind a dummy, and put that node's next into the heap if it is not null. Each of the N nodes enters and leaves the heap once, so the total is O(N log k) time and O(k) space.

What does the recursive version look like, and why is it not the default?

If a is null we return b, and if b is null we return a. Otherwise, if a.val <= b.val, we set a.next = merge(a.next, b) and return a, and if not, we set b.next = merge(a, b.next) and return b. Each call places one node and lets the next call merge the rest. It is short and correct, but every node adds a call that waits on the stack, so it uses O(n + m) space, and on lists of a few hundred thousand nodes it can throw a StackOverflowError.

Why does the comparison use <= rather than <?

With <=, a tie takes the node from list a first, so equal values keep the order they had, a from before b. A merge with this property is called stable, and merge sort relies on it to be a stable sort, which matters when we sort records by one field and want records with equal keys to stay in their original order. With < the result would still be sorted, only ties would come from b first.

9Conclusion

We merged two sorted lists by comparing only their fronts, hanging the smaller front node behind a dummy head, and attaching the leftover list with one link when the other ran out. The dummy removes the special case of an empty result, and reusing the nodes keeps the extra space at O(1), with O(n + m) time. The clue to remember is two sorted inputs and one sorted output: the smallest remaining item is always at one of the fronts, so a merge needs only one comparison per item.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the requirements: I splice the existing nodes rather than creating new ones, either list may be empty, and duplicates are kept. The simplest approach copies all values, sorts them and rebuilds a list, which is O((n + m) log(n + m)) and ignores the fact that both inputs are already sorted.

Then, if they want more

Since each list is sorted, the smallest remaining node is always one of the two heads, so I compare the heads and take the smaller. I use a dummy node in front of the result so that the first node needs no special case, and a tail reference to its last node.

While both lists have nodes, I hang the smaller head after tail, advance that list, and move tail forward. I use less than or equal so that ties come from the first list, which keeps the merge stable.

When one list runs out, the other list's remaining nodes are already sorted and all larger, so I attach them with one assignment. I return dummy.next. Each node is placed once, so it is O(n + m) time and O(1) extra space. For k lists I would use a min-heap of the k heads, which gives O(N log k).

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 59 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Merge two sorted linked lists into one sorted linked list.": https://scrivio-interview-library.netlify.app/data-structures/solutions/merge-two-sorted-linked-lists-into-one-sorted-linked-list-878d34/