Problem overview
The method mergeTwoLists receives list1 and list2, the heads of two singly linked lists that are each sorted in ascending order. It returns the head of one sorted list that contains every node of both. Either list can be empty, and an empty list is represented by null.
The nodes must be spliced together, not copied: the result reuses the existing ListNode objects and only changes their next fields. The lesson provides the ListNode class, with an int val, a ListNode next and constructors that take nothing, a value, or a value and a next node.
With list1 = 1->2->4 and list2 = 1->3->4 the method returns 1->1->2->3->4->4. With list1 = -4->10->12 and list2 = -7->0 it returns -7->-4->0->10->12, and with one empty list it returns the other list unchanged.
Approach: always take the smaller front node
Because both lists are sorted, the smallest value not yet placed is always one of the two front nodes. So the merge repeats one move: compare the fronts, attach the smaller node to the end of the merged list, and advance in the list it came from. This is the same merge step that merge sort uses.
Each node is attached once, so the running time is O(n + m) for lists of n and m nodes. No node is created, so the extra space is O(1).
The awkward part is the very first node. The merged list starts out empty, so the first attachment would need a special case: set the head instead of a next field. A dummy node removes it. It is a throwaway node placed in front of the real list, so the merged list is never empty, and every attachment looks the same: tail.next = something. The answer is dummy.next.
A recursive version is shorter to write, but it goes one call deeper per node. With up to 10,000 nodes in each list, a loop is the safer choice.
Step by step
- Create the dummy node with
new ListNode()and keep it indummy. Its value is never used. - Declare
tailand point it atdummy. It always stands on the last node of the merged list, which is where the next node is attached. - Loop while both lists have nodes. Once one list is empty there is nothing left to compare.
- Compare the fronts with
list1.val <= list2.val. Using<=means that on a tie the node fromlist1goes first, so equal values keep their original order. - Attach and advance. In the first branch, set
tail.next = list1and movelist1tolist1.next. Theelsebranch does the same withlist2. - Move
tailforward once, after theif/else, since both branches attach a node attail.next. - Attach the rest in one go. After the loop, at least one list is used up. The other one is already sorted and every value in it is at least as large as what was merged, so
tail.nextcan point at it directly. The conditionallist1 != null ? list1 : list2picks whichever list still has nodes. If both are used up, it pickslist2, which isnull, and that correctly ends the list. - Return
dummy.next, the first real node.
The solution in Java
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode();
ListNode tail = dummy;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
tail.next = list1;
list1 = list1.next;
} else {
tail.next = list2;
list2 = list2.next;
}
tail = tail.next;
}
tail.next = list1 != null ? list1 : list2;
return dummy.next;
}
}
Java details worth a look:
- Variables hold references.
tail.next = list1makestail.nextrefer to the same node object thatlist1refers to. Nothing is copied. Thenlist1 = list1.nextchanges only the local variablelist1, not the node. - The parameters are local. Reassigning
list1andlist2inside the method doesn't affect the caller's variables, though the nodes themselves are shared with the result. - Use
!= nulland==for references. Comparing a reference withnullis the one case where==is exactly what you want. Comparing theintvalues uses<=directly. - The conditional operator is an expression.
condition ? a : bevaluates toaorb, so it can sit on the right side of an assignment.
Complexity
Time: O(n + m). Each loop turn attaches one node and moves one list forward, so the loop runs at most n + m times. Attaching the leftover list is one assignment.
Space: O(1). The method creates one dummy node and uses two extra references. The merged list is built from the nodes already there.
Edge cases and common mistakes
- One or both lists empty. With
list1 = nullandlist2 = 0, the loop never runs,tail.nextbecomeslist2, and the result is0. With both empty,dummy.nextis stillnull. - Forgetting to move
tail. Then every new node overwrites the sametail.nextand the merged list loses nodes. - Returning
dummy. The dummy node is not part of the answer, and its value is meaningless. - Looping until both lists are empty. Once one list is
null,list1.valorlist2.valthrows aNullPointerException. The loop condition uses&&for that reason. - Creating new nodes. It still produces a correct list but uses
O(n + m)extra space, which breaks the lesson's constraint.
Testing
These results come from running the solution:
[1,2,4]and[1,3,4]give1->1->2->3->4->4.[]and[0]give0.[-4,10,12]and[-7,0]give-7->-4->0->10->12.[]and[]give an empty list (null).[1,5]and[2]give1->2->5, and the first node returned is the same object as the head of the first list.
