Problem overview
The function merge_two_lists receives the heads of two linked lists, list1 and list2, each sorted in ascending order. Each head is an Option<Box<ListNode>>, and None stands for an empty list. The function must return the head of one sorted list that contains all the nodes of both inputs.
The result has to be made by splicing: the existing nodes are linked to each other, and no new node holds a copied value. The lesson provides the ListNode struct, with a val: i32, a next: Option<Box<ListNode>> and a ListNode::new(val) constructor.
With list1 = [1, 2, 4] and list2 = [1, 3, 4] the result is [1, 1, 2, 3, 4, 4]. With list1 = [] and list2 = [0] it is [0], and with list1 = [-4, 10, 12] and list2 = [-7, 0] it is [-7, -4, 0, 10, 12]. Merging [] with [] gives [].
Approach: always take the smaller front node
Both lists are sorted, so the smallest value not yet used is always one of the two front nodes. Compare them, move the smaller one to the end of the merged list, and repeat. When one list runs out, the other one is already sorted and every node in it is at least as large as everything merged so far, so it can be attached whole.
The statement asks for O(n + m) time, where n and m are the list lengths: every node is moved exactly once, with one comparison at most. The extra space is O(1) because no node is created or copied, only re-linked.
A recursive merge is also possible, but it goes one call deeper for every node. With up to 10,000 nodes in each list, that can exhaust the call stack, so the lesson uses a loop.
The dummy node
Attaching the first node of the merged list is a special case: there is no previous node to attach it to. A dummy node removes that case. The merged list starts as a placeholder node with value 0, and a variable tail always points at the last node of the merged list, which is the dummy at first. Every node is then attached the same way, to tail.next, and the answer is dummy.next. The dummy's own value is never part of the result.
Step by step
- Create the dummy.
Box::new(ListNode::new(0))goes into a mutable variabledummy. The parameters are declaredmutin the signature, so the function can movelist1andlist2forward. - Point
tailat it withlet mut tail = &mut dummy;. It is a mutable reference, so writing totail.nextchanges the real node, and the variable itself ismutso it can later point to a different node. - Loop while both lists have nodes. Once one is empty, there is nothing left to compare.
- Compare the front values.
as_ref()borrows theOptionwithout moving it,unwrap()reaches the box, and.valreads the number. Using<=sends the node fromlist1first on a tie, which keeps equal values in a stable order. - Cut the front node off its list.
list1.as_mut().unwrap().next.take()moves the rest of the list out intorestand leavesNonebehind. Now the front node stands alone. - Attach it by moving
list1intotail.next. This moves the existing box, which is why no new memory is needed. - Advance the list:
list1 = rest;. Assigning tolist1after it was moved out is allowed, because it gets a fresh value. - The
elsebranch does the same three things forlist2. - Move
tailforward once, after theif/else, because both branches attach a node attail.next:tail = tail.next.as_mut().unwrap();. - Attach the leftovers. After the loop, at least one list is empty.
tail.nextbecomeslist1if it isSome, andlist2otherwise. If both are empty,list2isNone, which ends the list correctly. - Return
dummy.next, with no semicolon. If both inputs were empty, that is stillNone.
The solution in Rust
struct ListNode {
val: i32,
next: Option<Box<ListNode>>,
}
impl ListNode {
fn new(val: i32) -> Self {
ListNode { val, next: None }
}
}
impl Solution {
fn merge_two_lists(mut list1: Option<Box<ListNode>>, mut list2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut dummy = Box::new(ListNode::new(0));
let mut tail = &mut dummy;
while list1.is_some() && list2.is_some() {
if list1.as_ref().unwrap().val <= list2.as_ref().unwrap().val {
let rest = list1.as_mut().unwrap().next.take();
tail.next = list1;
list1 = rest;
} else {
let rest = list2.as_mut().unwrap().next.take();
tail.next = list2;
list2 = rest;
}
tail = tail.next.as_mut().unwrap();
}
tail.next = if list1.is_some() { list1 } else { list2 };
dummy.next
}
}
The Rust details worth a closer look:
- Ownership does the splicing. Each node is owned by the
Boxin the previous node'snext.tail.next = list1;moves ownership of the whole remaining chain oflist1into the merged list. That is only safe becausetake()already cut the rest off, so the moved chain is a single node. take()on anOptionreplaces the value withNoneand returns the old value. It is the standard way to move something out of a field you only borrow.as_ref()andas_mut()turn an&Option<Box<T>>into anOption<&Box<T>>, sounwrap()gives a reference and doesn't consume the list. Without them,list1.unwrap()would move the list out of the variable.- The reference and the dummy. While
tailborrowsdummy, nothing else may usedummy. The last use oftailis the assignment after the loop, so the borrow is over by the timedummy.nextmoves the answer out. ifis an expression.if list1.is_some() { list1 } else { list2 }produces one of the two lists as a value, so it can be assigned straight totail.next.- The tail is the last expression.
dummy.nexthas no semicolon, so it is the function's return value.
Complexity
Time: O(n + m). Each loop turn moves one node into the merged list, and the loop ends when one list is empty, after at most n + m - 1 turns. The leftover attach is a single assignment, not a walk.
Space: O(1). The function holds the dummy node and a few references. The nodes of the result are the input nodes.
Edge cases and common mistakes
- An empty list. With
[]and[0]the loop never runs,list1isNone, andtail.nextbecomeslist2, so the result is[0]. - Both empty. The result is
None, becausedummy.nextwas never set. - Unequal lengths.
[-4, 10, 12]and[-7, 0]use uplist2after three nodes, and the rest oflist1,10and12, follows without more comparisons. - Forgetting
take(). Movinglist1intotail.nextwithout cuttingnextfirst would drag the whole remaining list along, andrestwould have nothing to continue with. - Using
unwrap()withoutas_ref(). It moves the list out of its variable, and the next use of the variable fails to compile. - Returning
dummy. The placeholder value 0 would be the first node of the answer. The answer starts atdummy.next. - Using
<instead of<=. The values still come out sorted, but on a tie the node fromlist2would go first.
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[1, 2, 3]give[1,2,3,5].
