Reverse a Singly Linked List Recursive in DSA Rust - Time & Space Complexity
We want to understand how the time needed to reverse a linked list grows as the list gets longer.
How does the number of steps change when the list size increases?
Analyze the time complexity of the following code snippet.
fn reverse_recursive(head: Option>) -> Option> {
match head {
None => None,
Some(mut node) => {
if node.next.is_none() {
Some(node)
} else {
let next = node.next.take();
let new_head = reverse_recursive(next);
if let Some(mut next_node) = new_head.as_deref_mut() {
let mut tail = &mut next_node;
while let Some(ref mut next) = tail.next {
tail = next;
}
tail.next = Some(node);
}
node.next = None;
new_head
}
}
}
}
This function reverses a singly linked list by calling itself on the next node until it reaches the end, then rewires the links backward.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive call on the next node in the list.
- How many times: Once for each node in the list, so n times for a list of size n.
Each node causes one recursive call, so the steps grow directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 recursive calls and rewiring steps |
| 100 | About 100 recursive calls and rewiring steps |
| 1000 | About 1000 recursive calls and rewiring steps |
Pattern observation: The work grows linearly as the list gets longer.
Time Complexity: O(n)
This means the time to reverse the list grows in direct proportion to the number of nodes.
[X] Wrong: "Recursive reversal is faster because it uses recursion instead of loops."
[OK] Correct: Both recursion and loops visit each node once, so they take similar time. Recursion adds extra function call overhead but does not reduce the number of steps.
Understanding this helps you explain how recursion works on linked lists and shows you can analyze how your code scales with input size.
"What if we changed the recursive reversal to an iterative approach? How would the time complexity change?"
Practice
Solution
Step 1: Understand recursive reversal logic
In recursion, we reverse the list starting from the end by calling the function on the next node first.Step 2: Adjust pointers after recursion returns
After the recursive call returns, we set the next node's next pointer to the current node, effectively reversing the link.Final Answer:
Reverse the rest of the list first, then adjust the current node's next pointer -> Option AQuick Check:
Recursive reversal = reverse rest first [OK]
- Trying to swap node values instead of pointers
- Reversing pointers before recursive call
- Using iteration instead of recursion
Solution
Step 1: Identify correct ownership and return type
In Rust, linked lists use Option to represent nullable pointers with ownership.Step 2: Match function signature for recursive reversal
The function should take ownership of the list head and return the new head after reversal, so Option input and output is correct.Final Answer:
fn reverse_list(head: Option) -> Option -> Option CQuick Check:
Ownership with Option = fn reverse_list(head: Option) -> Option [OK]
- Using references without ownership causing borrow errors
- Returning plain Node instead of Option
- Passing mutable references incorrectly
fn reverse_list(head: Option) -> Option {
match head {
None => None,
Some(mut node) => {
if node.next.is_none() {
Some(node)
} else {
let next = node.next.take();
let new_head = reverse_list(next);
let mut tail = new_head.as_ref();
while let Some(t) = tail {
if t.next.is_none() {
break;
}
tail = t.next.as_ref();
}
tail.unwrap().next = Some(node);
node.next = None;
new_head
}
}
}
}Solution
Step 1: Analyze pointer manipulation and borrowing
The code tries to get a mutable reference to tail via as_ref() and then mutate tail.unwrap().next, which causes a borrowing error in Rust.Step 2: Understand Rust's borrowing rules
Rust does not allow mutable access through an immutable reference (as_ref()), so this code will cause a compile-time error.Final Answer:
Compile-time error due to borrowing -> Option DQuick Check:
Immutable ref then mutable write = error [OK]
- Ignoring Rust's strict borrowing rules
- Assuming as_ref() allows mutation
- Not using take() properly to avoid borrow conflicts
fn reverse_list(head: Option) -> Option {
match head {
None => None,
Some(mut node) => {
if node.next.is_none() {
Some(node)
} else {
let next = node.next.take();
let new_head = reverse_list(next);
node.next.as_mut().unwrap().next = Some(node);
node.next = None;
new_head
}
}
}
}Solution
Step 1: Understand effect of take() on node.next
Calling node.next.take() sets node.next to None, so node.next.as_mut() returns None.Step 2: Identify unsafe unwrap causing panic
Calling unwrap() on None causes a runtime panic, so node.next.as_mut().unwrap() is invalid after take().Final Answer:
Using node.next.as_mut().unwrap() after take() causes None unwrap panic -> Option BQuick Check:
unwrap on None after take() = panic [OK]
- Assuming node.next still exists after take()
- Ignoring unwrap panic possibility
- Not returning new_head properly
Solution
Step 1: Combine reversal and counting in recursion
Modify the recursive function to return both the new head and the count of nodes reversed as a tuple.Step 2: Increment count after each recursive call
Each recursive call returns the count from deeper calls; add 1 for the current node before returning.Final Answer:
Modify the recursive function to return a tuple (new_head, count) and increment count after each recursion. -> Option AQuick Check:
Return tuple (head, count) in recursion = Modify the recursive function to return a tuple (new_head, count) and increment count after each recursion. [OK]
- Using global variables causing unsafe code
- Counting nodes separately after reversal wastes time
- Ignoring counting during recursion
Ready to prove it?
Pass the test and this pattern moves unknown
