3.1Singly Linked List
- 3.1.1What is a singly linked list?
- 3.1.2Creating a singly linked list
- 3.1.3Traversal
- 3.1.4Inserting at the end
- 3.1.5Inserting at a position
- 3.1.6Inserting at the head
- 3.1.7Deleting from the end
- 3.1.8Deleting from the head
- 3.1.9Deleting from the middle
- 3.1.10Searching for a value
- 3.1.11Reversing a linked list (iterative)
- 3.1.12Reversing a linked list (recursive)
Reversing a linked list (recursive)
In the previous lesson we reversed the list with a loop and three pointers. The same task can be written much more briefly with recursion. The code is short, but to see how it works you have to follow the call stack; that is exactly what this lesson does.
- How to split the problem into "the first node and the rest" and solve it with recursion
- What the base case is and why it has two conditions
- How the call stack grows and shrinks, and why it can overflow on long lists
1Idea
In recursion a function calls itself on a smaller part of the problem. Split the list into the first node and the rest. reverseRecursive(head->next) reverses the rest and returns its new head (the old last node). That value is kept in rest and carried back, unchanged, all the way to the outermost call.
Once the rest is reversed, head->next still points to the old second node, which now sits at the end of the reversed part. head->next->next = head links it back to head. head->next = NULL makes head the new end of the list. Without that line the first two nodes point to each other.
The base case is where the function answers without calling itself again. If the list is empty or has one node, there is nothing to reverse and head is returned as it is. Without the second condition (head->next == NULL), the last node would read head->next->next through NULL.
Each call holds a frame on the call stack until it finishes. For a list of n nodes the stack grows n frames deep, so the extra memory is O(n). On a list with hundreds of thousands of nodes the stack can overflow; Python raises RecursionError at about 1000 frames by default. That is why the loop version is preferred for long lists.
Like the other two languages, the C version returns the new head. The caller writes it into its own pointer: head = reverseRecursive(head);.
2Step by step
The drawing reverses the list 12 → 7 → 3 with recursion. The stack under the drawing shows the calls that have not finished; the top one is running now. The head label shows that call's parameter.
- Start. The list is 12 → 7 → 3. No call has been made yet; the stack is empty.
- The first call starts with
head= 12. It is not the base case, because there is a node after 12. The function calls itself on the rest and waits. - The second call, with
head= 7. Again not the base case; one more frame goes on the stack and a call is made for 3. - The third call, with
head= 3. The next field of 3 is NULL: the base case. 3 is returned without changing any link, and this frame leaves the stack. - Back in the call for 7,
rest= 3.head->next->next = head: the link of 3 turns to 7. For a moment 7 and 3 point to each other. head->next = NULL: the link of 7 is cut and the cycle is gone. The call returnsrest(3) and leaves the stack.- Back in the call for 12,
restis still 3.head->nextpoints to 7; the link of 7 turns to 12. head->next = NULL: 12 becomes the new end of the list. The last call also returns 3 and leaves the stack.- Result: 3 → 7 → 12. The stack is empty. The returned value, 3, is the new head of the list.
struct Node { int data; struct Node* next;}; struct Node* reverseRecursive(struct Node* head) { if (head == NULL || head->next == NULL) // base case return head; struct Node* rest = reverseRecursive(head->next); head->next->next = head; // the next node points back to me head->next = NULL; return rest; // the new head}class Node { int data; Node next; Node(int data) { this.data = data; }} Node reverseRecursive(Node head) { if (head == null || head.next == null) // base case return head; Node rest = reverseRecursive(head.next); head.next.next = head; // the next node points back to me head.next = null; return rest; // the new head}class Node: def __init__(self, data): self.data = data self.next = None def reverse_recursive(head): if head is None or head.next is None: # base case return head rest = reverse_recursive(head.next) head.next.next = head # the next node points back to me head.next = None return rest # the new headThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
There is one call per node and each call does a fixed amount of work.
At the deepest point n calls sit on the stack together; each one holds a frame of memory.
The loop version does the same job with O(1) extra memory. What the recursive version offers is brevity: it mirrors the idea "reverse the rest, then put the first node at the end" directly.
4Common mistake
The most common mistake is forgetting the head->next = NULL line:
struct Node* rest = reverseRecursive(head->next);head->next->next = head;return rest; // head->next still points to the old second nodeEach call fixes the link of the inner nodes in the next call up, but nothing fixes the head of the outermost call. The old first node (12) still points to 7, and 7 points to 12, so the list has a cycle. Any code that tries to traverse the list loops forever.
5Try it
For a list of n nodes, how deep does the call stack get at most?
Which node does each call return?
The answer is B. The base case returns the last node. Every other call passes the rest it received back unchanged. So the outermost call also returns the old last node, the head of the reversed list.
Show the answer
The answer is B. The base case returns the last node. Every other call passes the rest it received back unchanged. So the outermost call also returns the old last node, the head of the reversed list.
Lessons you mark show up in the curriculum. This is kept on this device only.