Problem overview
The function mergeTwoLists receives list1 and list2, pointers to the first nodes of two linked lists. Each list is sorted in ascending order. It must return the head of a single sorted list that contains every node of both inputs. The nodes have to be spliced together: the existing nodes are re-linked, and no new ones are created. Either list can be empty, and an empty list is a nil pointer. The lesson provides the ListNode type, which has an integer Val and a Next pointer to the following node.
For list1 = [1, 2, 4] and list2 = [1, 3, 4] the merged list is [1, 1, 2, 3, 4, 4]. For list1 = [-4, 10, 12] and list2 = [-7, 0] it is [-7, -4, 0, 10, 12]: once list2 is used up, the rest of list1 follows as it is.
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
Because both lists are sorted, the smallest value not yet placed is always one of the two front nodes. Compare them, attach the smaller one to the end of the merged list, and advance in the list it came from. Every node is looked at once, so the time is linear in the total number of nodes. Nothing is allocated per node, because attaching is just assigning a pointer.
The awkward part is the first node: the merged list is empty at the start, so there is no node whose Next can be set. A dummy node removes that case. The merged list starts as one placeholder node, tail points at its last node, and every real node is attached after tail in the same way. At the end, the answer is the node after the placeholder.
A recursive merge is also possible, but it goes one call deeper for every node, so long lists need a lot of call stack. The loop uses a fixed amount of memory however long the lists are.
Step by step
- Create the placeholder.
&ListNode{}makes a zero-valued node and gives its address, which goes intodummy. The merged list will hang offdummy.Next. - Create
tail. It starts ondummy, which at this point is the whole merged list. - Loop while both lists have nodes. Go has no
while, so this is aforwith only a condition. When one list runs out, there is nothing left to compare. - Compare the front values 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 = list1, then movelist1to its next node. The node now belongs to the merged list, so what remains oflist1starts after it. - Mirror it for
list2in theelsebranch. - Move
tailforward once, after theif/else. Both branches attach a node attail.Next, so one shared line movestailonto it. - Attach the leftovers. After the loop, at least one list is empty. The other one is still sorted, and none of its nodes is smaller than what is already merged, so it can be attached whole. Go has no conditional operator, so an
if/elsechooses betweenlist1andlist2. - Return
dummy.Next. The dummy node itself is not part of the answer.
The solution in Go
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
dummy := &ListNode{}
tail := dummy
for list1 != nil && list2 != nil {
if list1.Val <= list2.Val {
tail.Next = list1
list1 = list1.Next
} else {
tail.Next = list2
list2 = list2.Next
}
tail = tail.Next
}
if list1 != nil {
tail.Next = list1
} else {
tail.Next = list2
}
return dummy.Next
}
Go details worth knowing:
- Pointers and
nil.*ListNodeis a pointer, and an empty list is thenilpointer. Go lets you writelist1.Valon a pointer without any dereferencing syntax, but doing it onnilpanics. The loop condition and the finalifmake sure that never happens. &ListNode{}and:=. The composite literal builds a node withVal0 andNextnil, and&takes its address.:=declares the variable and infers the type*ListNode.- Parameters are copies of the pointers. Moving
list1andlist2forward changes only the function's local copies, not the caller's variables. The nodes themselves are shared, so the returned list is made of the caller's original nodes. - The final
elseneeds noniltest. If both lists are empty,list2isnil, and assigning it totail.Nextcorrectly ends the list.
Complexity
Time: O(n + m). Each loop iteration attaches one node and moves one list forward, so the loop runs at most n + m times. Attaching the leftover is a single assignment.
Space: O(1). The function uses one dummy node and a few pointers, whatever the sizes of the lists. The merged list reuses the input nodes.
Edge cases and common mistakes
- Empty lists. With
[]and[0]the loop never runs, the leftover step attaches[0]and the result is[0]. With two empty lists the result isnil, which is the empty list. - Ties. With
[2, 2]and[2]the result is[2, 2, 2]. With<=, the first node of the result is alwayslist1's node when the fronts are equal. - Returning
dummyinstead ofdummy.Next. The result would start with an extra node of value 0. - Forgetting to move
tail. Each attachment would overwrite the previous one, and the merged list would keep only the last node. - Forgetting the leftover. If the loop ends and the remaining nodes are not attached, they are lost:
[-4, 10, 12]and[-7, 0]would end at 0. - Walking the leftover node by node. It works, but it is unnecessary, because the remaining nodes are already linked in order.
Testing
[1, 2, 4]and[1, 3, 4]gives[1, 1, 2, 3, 4, 4].[]and[0]gives[0].[-4, 10, 12]and[-7, 0]gives[-7, -4, 0, 10, 12].[]and[]gives[].[5]and[]gives[5].[2, 2]and[2]gives[2, 2, 2].
