Reverse a Singly Linked List Recursive in DSA C - Time & Space Complexity
We want to understand how the time needed to reverse a linked list grows as the list gets longer.
Specifically, how many steps does the recursive method take as the list size increases?
Analyze the time complexity of the following code snippet.
struct Node {
int data;
struct Node* next;
};
struct Node* reverseRecursive(struct Node* head) {
if (head == NULL || head->next == NULL) return head;
struct Node* rest = reverseRecursive(head->next);
head->next->next = head;
head->next = NULL;
return rest;
}
This code 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 of 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 number of steps grows 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 size increases.
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 than iterative reversal because recursion is magical."
[OK] Correct: Both recursive and iterative methods visit each node once, so they take similar time. Recursion adds extra overhead from function calls but does not reduce the total steps.
Understanding recursive reversal helps you think about how recursion works on linked structures, a key skill for many coding problems.
"What if we changed the recursion to an iterative loop? How would the time complexity change?"
