Java Linked List Program · OT12
Merge Two Sorted Linked Lists in Java
Repeatedly take the smaller head of the two lists and attach it to the result. No new nodes are created; the existing ones are relinked.
Problem Statement
Given the heads of two singly linked lists sorted in ascending order, merge them into one sorted list and return its head.
Reuse the existing nodes instead of creating new ones. Either list can be empty, and equal values may appear in both.
Input/Output Examples
1→4→7 and 2→3→8→9Output1→2→3→4→7→8→9Explanation: nodes are taken alternately by value.(empty) and 5→6Output5→6Explanation: the other list is returned as it is.2→2 and 2Output2→2→2Explanation: ties are fine; the first list goes first.Visual Explanation
- Compare 1, 2result1take 1 from list A
- Compare 4, 2result12take 2 from list B
- Compare 4, 3result123take 3 from list B
- …result12347A is used up after 7
- Attach restlink 8→9 in one step1→2→3→4→7→8→9
A dummy node in front of the result means the first real node is handled like every other node. When one list ends, the remaining list is already sorted, so it is attached with a single assignment.
Approaches
Both approaches relink the existing nodes. One uses a loop with a dummy head; the other expresses the merge recursively.
Approach 1: Iterative With a Dummy Node (Recommended)
Idea: keep a tail pointer and always link the smaller of the two current heads to it.
- Create a dummy node and set
tail = dummy. - While both lists have nodes, link the smaller head to
tailand advance that list. - Attach the non-empty remainder and return
dummy.next.
Time: O(n + m) · Space: O(1).
Approach 2: Recursion
Idea: the smaller head comes first, and its next is the merge of the rest.
- If one list is empty, return the other.
- Pick the smaller head.
- Set its
nextto the merge of its successor and the other list, then return it.
Time: O(n + m) · Space: O(n + m). One stack frame per node.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Iterative With a Dummy Node (Recommended)
Using <= keeps equal values in their original list order, which makes the merge stable.
public class MergeListsIterative {
static class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
// A dummy head avoids a special case for the first node; existing nodes are relinked
static Node merge(Node a, Node b) {
Node dummy = new Node(0);
Node 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; // attach whatever is left
return dummy.next;
}
static Node of(int... values) {
Node dummy = new Node(0);
Node t = dummy;
for (int v : values) {
t = t.next = new Node(v);
}
return dummy.next;
}
static String show(Node n) {
if (n == null) {
return "(empty)";
}
StringBuilder sb = new StringBuilder();
for (; n != null; n = n.next) {
sb.append(n.val).append(n.next != null ? "->" : "");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(show(merge(of(1, 4, 7), of(2, 3, 8, 9))));
System.out.println(show(merge(of(), of(5, 6))));
System.out.println(show(merge(of(2, 2), of(2))));
}
}
1->2->3->4->7->8->9 5->6 2->2->2
Time complexity: O(n + m) · Space complexity: O(1).
Approach 2: Recursion
Very short, but long lists can overflow the call stack.
public class MergeListsRecursive {
static class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
// The smaller head comes first; its next is the merge of everything that is left
static Node merge(Node a, Node b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
if (a.val <= b.val) {
a.next = merge(a.next, b);
return a;
}
b.next = merge(a, b.next);
return b;
}
static Node of(int... values) {
Node dummy = new Node(0);
Node t = dummy;
for (int v : values) {
t = t.next = new Node(v);
}
return dummy.next;
}
static String show(Node n) {
if (n == null) {
return "(empty)";
}
StringBuilder sb = new StringBuilder();
for (; n != null; n = n.next) {
sb.append(n.val).append(n.next != null ? "->" : "");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(show(merge(of(1, 4, 7), of(2, 3, 8, 9))));
System.out.println(show(merge(of(), of(5, 6))));
System.out.println(show(merge(of(2, 2), of(2))));
}
}
1->2->3->4->7->8->9 5->6 2->2->2
Time complexity: O(n + m) · Space complexity: O(n + m).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Iterative With a Dummy Node | O(n + m) | O(1) |
| Recursion | O(n + m) | O(n + m) |
Here n and m are the lengths of the lists. Each node is linked once. The loop uses constant memory; the recursion uses one stack frame per node.
Interview Tips and Recommended Approach
- Use a dummy node. It removes the special case for choosing the first node.
- Attach the remainder in one step. There is no need to loop over what is left.
- Prefer the loop for long lists. The recursive version can throw
StackOverflowError. - Know where it is used: this merge is the core of merge sort on linked lists and of merging k sorted lists.
Recommended Approach: Iterative With a Dummy Node
Why: it relinks nodes in place with constant extra memory and has no recursion depth limit.