Bird
Raised Fist0
DSA Rustprogramming~20 mins

Reverse a Singly Linked List Recursive in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Recursive Reverse Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Recursive Reverse on 1->2->3->null
What is the printed state of the linked list after recursively reversing the list 1 -> 2 -> 3 -> null?
DSA Rust
struct Node {
    val: i32,
    next: Option<Box<Node>>,
}

fn reverse_recursive(head: Option<Box<Node>>) -> Option<Box<Node>> {
    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);
                let mut tail = new_head.as_ref();
                while let Some(t) = tail {
                    if t.next.is_none() {
                        break;
                    }
                    tail = t.next.as_ref();
                }
                if let Some(t) = tail {
                    let raw_tail = unsafe { &mut *(t as *const _ as *mut _) };
                    raw_tail.next = Some(node);
                }
                node.next = None;
                new_head
            }
        }
    }
}

fn print_list(head: &Option<Box<Node>>) {
    let mut current = head.as_ref();
    while let Some(node) = current {
        print!("{} -> ", node.val);
        current = node.next.as_ref();
    }
    println!("null");
}

fn main() {
    let node3 = Box::new(Node { val: 3, next: None });
    let node2 = Box::new(Node { val: 2, next: Some(node3) });
    let node1 = Box::new(Node { val: 1, next: Some(node2) });

    let head = Some(node1);
    let reversed = reverse_recursive(head);
    print_list(&reversed);
}
A3 -> 1 -> 2 -> null
B1 -> 2 -> 3 -> null
Cnull
D3 -> 2 -> 1 -> null
Attempts:
2 left
💡 Hint
Think about how recursion reaches the last node and then reverses the links on the way back.
❓ Predict Output
intermediate
1:00remaining
Output of Recursive Reverse on Empty List
What is the printed state of the linked list after recursively reversing an empty list (null)?
DSA Rust
fn main() {
    let head: Option<Box<Node>> = None;
    let reversed = reverse_recursive(head);
    print_list(&reversed);
}
Anull
B0 -> null
Cpanic! error
DNone
Attempts:
2 left
💡 Hint
What happens when the input list is empty?
🔧 Debug
advanced
2:30remaining
Identify the Bug in Recursive Reverse Implementation
Which option shows the bug that causes infinite recursion or stack overflow in this recursive reverse function?
DSA Rust
fn reverse_recursive(head: Option<Box<Node>>) -> Option<Box<Node>> {
    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);
                node.next.as_mut().unwrap().next = Some(node);
                node.next = None;
                new_head
            }
        }
    }
}
Anode.next.take() is not called, so next is never None
BMissing base case for None causes infinite recursion
Cnode.next.as_mut().unwrap().next = Some(node); causes infinite recursion because node is moved into itself
DThe function returns None always
Attempts:
2 left
💡 Hint
Check how the pointers are reassigned after recursion call.
🧠 Conceptual
advanced
1:30remaining
Why Use Recursion to Reverse a Linked List?
Which is the main advantage of using recursion to reverse a singly linked list compared to iteration?
ARecursion naturally reverses the list by unwinding the call stack, making code simpler and cleaner
BRecursion avoids changing pointers
CRecursion is faster than iteration for linked lists
DRecursion uses less memory than iteration
Attempts:
2 left
💡 Hint
Think about how recursion processes nodes from the end back to the start.
❓ Predict Output
expert
3:00remaining
Output After Recursive Reverse on 1->2->3->4->null with Print Statements
Given the recursive reverse function below with added print statements, what is the exact output when reversing the list 1 -> 2 -> 3 -> 4 -> null?
DSA Rust
struct Node {
    val: i32,
    next: Option<Box<Node>>,
}

fn reverse_recursive(head: Option<Box<Node>>) -> Option<Box<Node>> {
    match head {
        None => {
            println!("Reached end: None");
            None
        },
        Some(mut node) => {
            println!("Visiting node: {}", node.val);
            if node.next.is_none() {
                println!("Base case reached at node: {}", node.val);
                Some(node)
            } else {
                let next = node.next.take();
                let new_head = reverse_recursive(next);
                let mut tail = new_head.as_ref();
                while let Some(t) = tail {
                    if t.next.is_none() {
                        break;
                    }
                    tail = t.next.as_ref();
                }
                if let Some(t) = tail {
                    let raw_tail = unsafe { &mut *(t as *const _ as *mut _) };
                    raw_tail.next = Some(node);
                }
                node.next = None;
                new_head
            }
        }
    }
}

fn print_list(head: &Option<Box<Node>>) {
    let mut current = head.as_ref();
    while let Some(node) = current {
        print!("{} -> ", node.val);
        current = node.next.as_ref();
    }
    println!("null");
}

fn main() {
    let node4 = Box::new(Node { val: 4, next: None });
    let node3 = Box::new(Node { val: 3, next: Some(node4) });
    let node2 = Box::new(Node { val: 2, next: Some(node3) });
    let node1 = Box::new(Node { val: 1, next: Some(node2) });

    let head = Some(node1);
    let reversed = reverse_recursive(head);
    print_list(&reversed);
}
A
Visiting node: 1
Visiting node: 2
Visiting node: 3
Base case reached at node: 3
4 -&gt; 3 -&gt; 2 -&gt; 1 -&gt; null
B
Visiting node: 1
Visiting node: 2
Visiting node: 3
Visiting node: 4
Base case reached at node: 4
4 -&gt; 3 -&gt; 2 -&gt; 1 -&gt; null
C
Base case reached at node: 4
Visiting node: 3
Visiting node: 2
Visiting node: 1
4 -&gt; 3 -&gt; 2 -&gt; 1 -&gt; null
D
Visiting node: 4
Visiting node: 3
Visiting node: 2
Visiting node: 1
Base case reached at node: 1
1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; null
Attempts:
2 left
💡 Hint
Trace the recursive calls from head to tail and back.

Practice

(1/5)
1. What is the main idea behind reversing a singly linked list using recursion?
easy
A. Reverse the rest of the list first, then adjust the current node's next pointer
B. Swap the values of the first and last nodes only
C. Iterate through the list and reverse pointers in a loop
D. Create a new list and copy elements in reverse order

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Reverse the rest of the list first, then adjust the current node's next pointer -> Option A
  4. Quick Check:

    Recursive reversal = reverse rest first [OK]
Hint: Think: reverse tail first, then fix current link [OK]
Common Mistakes:
  • Trying to swap node values instead of pointers
  • Reversing pointers before recursive call
  • Using iteration instead of recursion
2. Which of the following Rust function signatures correctly represents a recursive function to reverse a singly linked list?
easy
A. fn reverse_list(head: Node) -> Node
B. fn reverse_list(head: &mut Node) -> &mut Node
C. fn reverse_list(head: Option) -> Option
D. fn reverse_list(head: &Node) -> Node

Solution

  1. Step 1: Identify correct ownership and return type

    In Rust, linked lists use Option to represent nullable pointers with ownership.
  2. 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.
  3. Final Answer:

    fn reverse_list(head: Option) -> Option -> Option C
  4. Quick Check:

    Ownership with Option = fn reverse_list(head: Option) -> Option [OK]
Hint: Use Option for linked list nodes in Rust [OK]
Common Mistakes:
  • Using references without ownership causing borrow errors
  • Returning plain Node instead of Option
  • Passing mutable references incorrectly
3. Given the following Rust code snippet for recursive reversal, what will be the output list after reversal if the input list is 1 -> 2 -> 3 -> null?
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
            }
        }
    }
}
medium
A. 3 -> 2 -> 1 -> null
B. 1 -> 2 -> 3 -> null
C. 2 -> 3 -> 1 -> null
D. Compile-time error due to borrowing

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Compile-time error due to borrowing -> Option D
  4. Quick Check:

    Immutable ref then mutable write = error [OK]
Hint: Check mutable vs immutable references in Rust code [OK]
Common Mistakes:
  • Ignoring Rust's strict borrowing rules
  • Assuming as_ref() allows mutation
  • Not using take() properly to avoid borrow conflicts
4. Identify the bug in this recursive Rust function to reverse a singly linked list:
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
            }
        }
    }
}
medium
A. Function does not return the new head
B. Using node.next.as_mut().unwrap() after take() causes None unwrap panic
C. Missing base case for empty list
D. No bug, code is correct

Solution

  1. 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.
  2. 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().
  3. Final Answer:

    Using node.next.as_mut().unwrap() after take() causes None unwrap panic -> Option B
  4. Quick Check:

    unwrap on None after take() = panic [OK]
Hint: Don't unwrap after take() without checking for None [OK]
Common Mistakes:
  • Assuming node.next still exists after take()
  • Ignoring unwrap panic possibility
  • Not returning new_head properly
5. You want to reverse a singly linked list recursively in Rust, but also count how many nodes were reversed. Which approach correctly combines reversal and counting? Options: A) Modify the recursive function to return a tuple (new_head, count) and increment count after each recursion. B) Use a global mutable variable to count nodes during recursion. C) Reverse the list first, then iterate again to count nodes. D) Count nodes before reversal and ignore during recursion.
hard
A. Modify the recursive function to return a tuple (new_head, count) and increment count after each recursion.
B. Use a global mutable variable to count nodes during recursion.
C. Reverse the list first, then iterate again to count nodes.
D. Count nodes before reversal and ignore during recursion.

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Modify the recursive function to return a tuple (new_head, count) and increment count after each recursion. -> Option A
  4. Quick 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]
Hint: Return (head, count) tuple from recursion to track nodes [OK]
Common Mistakes:
  • Using global variables causing unsafe code
  • Counting nodes separately after reversal wastes time
  • Ignoring counting during recursion
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard