Problem overview
The function 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. The head of an empty list is a null pointer, so either input, or both, can be empty.
The lesson provides the node type, as a comment above the class: a ListNode with an int val, a ListNode *next and three constructors. The default constructor sets val to 0 and next to nullptr.
With list1 = [1,2,4] and list2 = [1,3,4], the function returns [1,1,2,3,4,4]. With list1 = [-4,10,12] and list2 = [-7,0], the result is [-7,-4,0,10,12]. When one list is empty, the answer is the other list as it is.
The statement asks for the nodes to be spliced together: the result is built by changing next pointers of the nodes that already exist, not by copying values into new nodes. It also sets a budget of O(n + m) time and O(1) extra space.
Approach: always take the smaller front node
Because both lists are sorted, the smallest value not yet used is always at the front of one of them. So the merge repeats one decision: compare the two front nodes, move the smaller one to the end of the merged list, and advance in the list it came from. Each node is moved once, which gives O(n + m) time. No new nodes are needed, so the extra space is constant.
The awkward part is the very first node. The merged list is empty at the start, so there is no "last node" to attach to. The usual fix is a dummy node: a throwaway node placed in front of the merged list. Then the merged list is never empty, every node is attached to a last node in the same way, and the answer is whatever hangs after the dummy.
A recursive merge is also possible ("the smaller head, followed by the merge of the rest"), but it goes one call deeper for each node. With up to 20,000 nodes in total, a loop is the safer choice.
When the two front values are equal, the lesson takes the node from list1 first. The result is the same sorted sequence either way, but this rule keeps equal values in a predictable order: the ones from list1 come before the ones from list2.
Step by step
- Create the dummy.
new ListNode()allocates a node on the heap and returns a pointer to it, which goes intodummy. Its value doesn't matter. - Create
tail. It points at the last node of the merged list. For now the merged list is just the dummy, sotailstarts there. - Loop while both lists have nodes. A pointer is true when it isn't null, so
list1 && list2is the whole condition. Once either list runs out, there is nothing left to compare. - Compare the front values with
list1->val <= list2->val. The<=is what makes ties go tolist1. - Attach the chosen node:
tail->next = list1. This links the node itself. - Advance
list1tolist1->next, because the node it pointed at now belongs to the merged list. - Write the mirror image in the
elsebranch forlist2: attach it, then advance it. - Move
tailtotail->next, the node just attached. Both branches end the same way, so this line sits after theif/else. - Attach the leftovers. After the loop, at least one list is empty. The other one is sorted and every value in it is at least as large as what was merged, so it can follow as it is.
list1 ? list1 : list2picks whichever is not null. If both are null, the merged list correctly ends with a null pointer. - Return
dummy->next, the first real node. The dummy is not part of the answer.
The solution in C++
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* dummy = new ListNode();
ListNode* tail = dummy;
while (list1 && list2) {
if (list1->val <= list2->val) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
tail->next = list1 ? list1 : list2;
return dummy->next;
}
};
The C++ details worth a closer look:
- Pointers in conditions. A null pointer converts to
falseand any other pointer totrue, which is whywhile (list1 && list2)andlist1 ? list1 : list2work without comparing tonullptr. ->against..list1->valis shorthand for(*list1).val. Use->on a pointer to a node.- The parameters are copies of the pointers. Assigning
list1 = list1->nextmoves the local pointer only. The caller's variable still points at its original head, and the nodes themselves are shared, not copied. - The lists are changed. After the call, the nodes of both inputs are linked into one chain. The caller must use the returned head and stop using the old heads as separate lists: at most one of them is still the first node, and the other now sits somewhere inside the merged chain.
- The dummy is never freed.
newallocates one node that this code never deletes, so each call leaks a single node. A stack-allocated dummy,ListNode dummy; ListNode* tail = &dummy;, avoids that and returnsdummy.next. The lesson's version is what its tests expect, and one small node per call is harmless there, but the stack form is the better habit.
Complexity
Time: O(n + m). Each turn of the loop attaches one node and advances at least one pointer, so the loop runs at most n + m times. Attaching the leftovers is one assignment, however long they are.
Space: O(1). The only allocation is the dummy node, plus a few pointers. The merged list reuses the input nodes, and the loop has no recursion, so the call stack doesn't grow with the input.
Edge cases and common mistakes
- Both lists empty. The loop never runs,
tail->nextbecomesnullptrand the function returnsnullptr: an empty list. - One list empty.
[]and[0]skip the loop and the leftover step attaches[0], so the result is[0]. - One list much longer. In the example with
[-4,10,12]and[-7,0], the loop stops after three comparisons and10->12is attached in one step. - Equal values.
[1,1]merged with[1,1]gives four 1s. With<=, a front node oflist1that ties with one oflist2is taken first. - Forgetting to advance
tail. The next node would overwritetail->next, and the merged list would keep only the last attached node. - Forgetting the leftover step. The nodes left in the longer list would be lost.
- Returning
dummy. That would put a bogus extra node, with value 0, at the front of the answer. - Recursion on long lists. A recursive merge uses one stack frame per node, which can overflow the stack on inputs with tens of thousands of nodes.
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[].[5]and[]give[5].[1,1]and[1,1]give[1,1,1,1].- Two lists of 20,000 nodes each (values 0 to 19999) give a list of 40,000 nodes, with no stack problems.
