Walk through both lists at the same time, always attaching the smaller head node to the result. A dummy head node avoids special cases for the first element.
public class MergeSortedLists {
static class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
static Node merge(Node a, Node b) {
Node dummy = new Node(0), tail = dummy;
while (a != null && b != null) {
if (a.val <= b.val) {
tail.next = a;
a = a.next;
} else {
tail.next = b;
b = b.next;
}
tail = tail.next;
}
tail.next = (a != null) ? a : b;
return dummy.next;
}
static Node of(int... values) {
Node dummy = new Node(0), cur = dummy;
for (int v : values) { cur.next = new Node(v); cur = cur.next; }
return dummy.next;
}
public static void main(String[] args) {
Node merged = merge(of(1, 3, 5, 7), of(2, 3, 6, 8, 10));
StringBuilder sb = new StringBuilder();
for (Node n = merged; n != null; n = n.next) {
sb.append(n.val).append(n.next != null ? " -> " : "");
}
System.out.println(sb);
}
}1 -> 2 -> 3 -> 3 -> 5 -> 6 -> 7 -> 8 -> 10
A recursive version is shorter (merge the smaller head with the result of merging the rest) but uses O(n + m) stack space and can overflow on very long lists.
Mention the dummy node explicitly; it is the detail interviewers look for because it removes the special case for the head.
A concise interview answer is
I use a dummy head and a tail pointer, repeatedly attach the smaller of the two current nodes, and when one list is empty I attach the remainder of the other. It relinks existing nodes, so it runs in O(n + m) time with O(1) extra space.
Last updated: 11 November 2026
Previous question: Find the length of the longest substring without repeating characters.
Next question: Rotate an n × n matrix by 90 degrees clockwise in place.