Merging two sorted linked lists
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Merging two sorted linked lists is a classic pointer-manipulation problem. Because each input list is already sorted, the merge can be done in one linear pass by repeatedly choosing the smaller current node and attaching it to the output list.
The Core Idea
Suppose you have:
- list A:
1 -> 3 -> 5 - list B:
2 -> 4 -> 6
You do not need to resort all nodes. Instead, compare the current heads of the two lists:
- take
1, because it is smaller than2 - then compare
3and2 - take
2 - continue until one list is exhausted
At the end, append the remaining nodes from the non-empty list.
This works because both inputs are already sorted.
Iterative Solution with a Dummy Node
The cleanest implementation uses a dummy head node so you do not need special-case logic for the first real element.
This reuses the existing nodes instead of creating a whole new list.
Building a Small Test
Output:
Recursive Version
There is also an elegant recursive solution:
This is concise and expressive, but the iterative version is often preferred in production because it avoids recursion-depth concerns and makes control flow easier to trace.
Complexity
If the two lists have lengths m and n:
- time complexity is
O(m + n) - extra space is
O(1)for the iterative version
Each node is visited exactly once, and no sorting pass is needed.
Why Linked Lists Make This Interesting
The same merge idea works for arrays, but linked lists emphasize pointer management. You are not writing into indexed positions. You are relinking next references carefully.
That makes this problem a useful test of:
- list traversal
- pointer updates
- edge-case handling
It also appears inside merge sort on linked lists, where merging is the efficient final step after splitting.
Common Pitfalls
The most common mistake is forgetting to advance the tail pointer after attaching a node. That can create cycles or overwrite links incorrectly.
Another error is forgetting to append the remainder after one list ends. The merge loop stops when either list becomes empty, but the other list may still contain valid sorted nodes.
People also sometimes create new nodes unnecessarily when the problem allows reusing the existing ones. Reusing nodes is simpler and more memory efficient.
Finally, be careful with empty-list inputs. If either list is None, the result should simply be the other list.
Summary
- Merge two sorted linked lists by repeatedly taking the smaller head node.
- A dummy head node makes the iterative solution cleaner.
- The iterative version runs in
O(m + n)time withO(1)extra space. - A recursive version is elegant, but iterative code is often safer in practice.
- Correct tail updates and final remainder attachment are the key implementation details.

