Problem overview
The method MergeTwoLists receives list1 and list2, the heads of two singly linked lists whose values are in ascending order. It returns the head of one sorted list that contains all the nodes of both. The nodes are re-linked, not copied: no new nodes are created for the result. Either list can be empty, and an empty list is represented by null.
The lesson provides the ListNode class, with an int val field, a ListNode next field and constructors that set them. You only write the method.
For [1,2,4] and [1,3,4] the result is [1,1,2,3,4,4]. For [] and [0] it is [0], and for [-4,10,12] and [-7,0] it is [-7,-4,0,10,12]. The target is O(n + m) time and O(1) extra space, where n and m are the two lengths.
Approach: always take the smaller front node
Both lists are already sorted, so the smallest value not yet used is always at the front of one of them. Compare the two front nodes, move the smaller one to the end of the merged list, and repeat. Each node is moved once, which gives O(n + m) time. Because nodes are re-linked rather than copied, the extra memory is a few references.
The awkward part is the very first node. The merged list is empty at the start, so "attach after the last node" has no last node. You could special-case the first attachment, but a cleaner trick is a dummy node: an extra node placed in front of the merged list. It makes the merged list non-empty from the start, so every real node is attached the same way, after a tail reference that points at the current last node. At the end the answer is dummy.next, and the dummy itself is thrown away.
When one list runs out, you don't need to compare anymore. The rest of the other list is sorted and none of its values is smaller than what is already merged, so the whole remainder can be attached in one assignment.
Step by step
- Create the dummy node with
new ListNode(). Itsvalis never used. - Point
tailat the dummy. Right now the merged list is only the dummy, so the dummy is also its last node. - Loop while both lists have nodes. The condition is
list1 != null && list2 != null. Once either isnull, there is nothing left to choose between. - Compare the front values with
list1.val <= list2.val. Using<=sends equal values tolist1first, so the merge is stable: among equal values,list1's nodes come beforelist2's. - Attach and advance in the first branch: set
tail.next = list1, thenlist1 = list1.next. The node you just attached is now part of the merged list, so what remains oflist1starts after it. - Do the mirror image in the
elsebranch forlist2. - Move
tailforward withtail = tail.next, after theif/else. Both branches attach a node attail.next, so this line is shared. - Attach the leftover after the loop with the conditional operator:
list1 != null ? list1 : list2. If both are used up, this isnull, which correctly ends the list. - Return
dummy.next, the first real node. If both inputs were empty it isnull, an empty list.
The solution in C#
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;
}
}
The C# details worth knowing:
ListNodeis a class, so variables hold references.tail.next = list1makes the merged list point at the very same node object, not a copy. That is why no extra memory is needed, and also why the input lists are damaged: after the merge, the originallist1andlist2heads are part of the merged list, and theirnextfields have been rewritten.list1andlist2are ordinary local variables. Assigninglist1 = list1.nextmoves the local reference only. The caller's variable still points at the old head.- Comparing with
nulluses==and!=. For a class likeListNode, which doesn't overload them, they compare references, andnullmeans "no node". - The conditional operator needs both branches to be one type. Here both are
ListNode, socond ? list1 : list2is fine, and the result can be assigned straight totail.next. - The dummy's fields are default values.
new ListNode()leavesvalat 0 andnextatnull. The value doesn't matter, because the dummy is never compared and is not part of the answer.
Complexity
Time: O(n + m). Each loop turn attaches one node and advances one of the two lists, so the loop runs at most n + m times. The leftover is attached with a single assignment, no matter how long it is.
Space: O(1). The method uses three references, dummy, tail and the two parameters, whatever the input size. A recursive version that merges the rest of the lists after choosing one node would use a call-stack frame per node, and lists of up to 20,000 nodes in total can overflow the stack. The loop avoids that.
Edge cases and common mistakes
- Both lists empty. The loop doesn't run,
tail.nextbecomesnull, anddummy.nextisnull. - One list empty. The loop doesn't run, and the other list is attached whole.
- Equal values. With
<=, the node fromlist1goes first. With two single nodes of value 7, the returned head islist1's node and itsnextislist2's node. Using<would still give a sorted result but would swap which node comes first. - Forgetting to advance
tail. Every new node would overwritetail.next, and the merged list would end up with only the last attached node and the leftover. - Forgetting the leftover. If one list is longer, its remaining nodes would be dropped from the result.
- Returning
dummyinstead ofdummy.next. The result would start with an extra node holding 0. - Not moving
list1orlist2. The same node would be compared and attached over and over, which makes the loop endless.
Testing
Each pair below was run through the method, and the merged lists print as shown.
[1,2,4]and[1,3,4]give[1,1,2,3,4,4].[]and[0]give[0].[-4,10,12]and[-7,0]give[-7,-4,0,10,12].[]and[]give[], and the returned head isnull.[5]and[]give[5].[2,2]and[2]give[2,2,2].- Two lists of 10,000 nodes each, one holding the even numbers and the other the odd numbers, merge into 20,000 nodes without a stack problem.
