Problem overview
mergeTwoLists receives list1 and list2, the heads of two singly linked lists that are each sorted in ascending order. It must return the head of one sorted list that contains all the nodes of both. The merge splices the existing nodes together: it changes their next links and creates no copies. An empty list is represented by null, and either input, or both, can be empty.
The lesson provides the node class. Each node has a field val holding an Int, which is why the code writes it in backticks, and a field next pointing to the following node or null. Its val parameter has a default of 0, so ListNode() builds a node holding 0.
For list1 = [1,2,4] and list2 = [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 statement asks for O(n + m) time and O(1) extra space, where n and m are the two lengths.
Approach: always take the smaller front node
Because both lists are sorted, the smallest value not yet placed is always at the front of one of them. So the merge repeats one move: compare the two front nodes, attach the smaller one to the end of the merged list, and advance in the list it came from. Each node is attached once, so the loop does at most n + m steps.
When one list runs out, the other still holds a sorted run of nodes that are all at least as large as everything merged so far. Nothing remains to compare, so that whole run can be hooked on in one assignment.
The only awkward part is the very first node. The merged list is empty at that point, so there is no last node to attach to. The lesson avoids a special case with a dummy node: a throwaway node placed in front of the merged list. A tail variable starts on the dummy and always stands on the merged list's last node. Every node, the first one included, is attached with tail.next = ..., and the answer is dummy.next.
A recursive merge is shorter to write, but it makes one call per node, so two lists of 10,000 nodes mean 20,000 nested calls. The loop uses no call stack, and that is what the lesson builds.
Step by step
- Copy the parameters into variables. Scala parameters can't be reassigned, and the code has to walk along both lists.
node1andnode2arevars that start at the two heads and always stand on the front node of what is left of each list. - Create the dummy.
ListNode()goes in aval, since the dummy itself never changes. The merged list hangs offdummy.next. - Declare
tail. It is avarbecause it moves, and it starts on the dummy, which at that moment is the whole merged list. - Loop while both lists have nodes. Once either front is
null, there is nothing to choose between. - Compare the front values with
<=. On a tie the node fromlist1goes first, so equal values keep their original order. - Attach and advance. In the
ifbranch,tail.nextbecomesnode1andnode1moves to its ownnext. Theelsebranch does the same fornode2. - Move
tailforward once, after theif/else, because both branches attached a node attail.next. - Attach the leftovers. After the loop,
tail.nextbecomesnode1if that is notnull, andnode2otherwise. If both are used up,node2isnull, which correctly ends the list. - Return
dummy.nextas the last expression. It is the first real node, ornullwhen both inputs were empty.
The solution in Scala
class Solution {
def mergeTwoLists(list1: ListNode, list2: ListNode): ListNode = {
var node1 = list1
var node2 = list2
val dummy = ListNode()
var tail = dummy
while (node1 != null && node2 != null) {
if (node1.`val` <= node2.`val`) {
tail.next = node1
node1 = node1.next
} else {
tail.next = node2
node2 = node2.next
}
tail = tail.next
}
tail.next = if (node1 != null) node1 else node2
dummy.next
}
}
The Scala details worth a closer look:
- Backticks around
val.valis a keyword, so a field with that name can only be written asnode1.`val`. Without the backticks the code does not compile. ifis an expression.if (node1 != null) node1 else node2produces a value, so it can sit on the right-hand side of an assignment. Both branches areListNodes, so the types agree.- No
new. Scala 3 lets you create an instance withListNode(), as if the class were a function.new ListNode()means the same. nullcomparisons.node1 != nullcompares values and works withnulltoo. Avarholding a node reference is rebindable, but assigning tonode1never changes the caller'slist1.- The last expression is the result.
dummy.nexthas noreturnin front of it, and its type,ListNode, matches the declared return type.
Complexity
Time: O(n + m). Each iteration of the loop attaches one node and advances one of the two pointers, and no pointer ever moves back, so the loop runs at most n + m times. The leftover attachment is a single assignment.
Space: O(1). The code allocates one dummy node and four variables, however long the lists are. The nodes in the result are the input nodes, relinked.
Edge cases and common mistakes
- An empty list. With
list1 = nullthe loop never runs andtail.nextbecomeslist2, so the result islist2as it is. With both lists empty the function returnsnull. - Returning
dummy. The dummy holds a placeholder 0 and is not part of the answer. The result starts atdummy.next. - Forgetting to advance
tail. Each new attachment would overwrite the previous one, and the result would lose nodes. - Forgetting the leftovers. For
[-4,10,12]and[-7,0]the loop ends after 0 is attached, and10and12would be dropped without the final line. - Using
<instead of<=. The merged values would still be sorted, but equal values fromlist2would go first. Using<=keeps list1's nodes ahead on a tie. - Merging two lists with equal values. Merging
[1,1,1]and[1,2]gives[1,1,1,1,2].
Testing
[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.- Merging two lists of 10,000 nodes each, one with the even numbers and one with the odd numbers, gives a sorted list of 20,000 nodes.
- For two single-node lists holding 5, the returned head is the node from
list1, and itsnextis the node fromlist2.
