algoritmauzmanı
TREN
3.1Singly Linked List
Lesson 3.1.12

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 . The code is short, but to see how it works you have to follow the ; that is exactly what this lesson does.

What you will learn
  • How to split the problem into "the first node and the rest" and solve it with recursion
  • What the is and why it has two conditions
  • How the call stack grows and shrinks, and why it can overflow on long lists
8 minTime O(n)Memory O(n)C · Java · Python

1Idea

In 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 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 .

Each call holds a frame on the until it finishes. For a list of n nodes the stack grows n frames deep, so the extra memory is . 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.

NULL12?7?3?headrest
Call stack
  1. Start. The list is 12 → 7 → 3. No call has been made yet; the stack is empty.
  2. 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.
  3. 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.
  4. The third call, with head = 3. The field of 3 is : the . 3 is returned without changing any link, and this frame leaves the stack.
  5. 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.
  6. head->next = NULL: the link of 7 is cut and the cycle is gone. The call returns rest (3) and leaves the stack.
  7. Back in the call for 12, rest is still 3. head->next points to 7; the link of 7 turns to 12.
  8. head->next = NULL: 12 becomes the new end of the list. The last call also returns 3 and leaves the stack.
  9. 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 head

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

There is one call per node and each call does a fixed amount of work.

Memory
O(n)

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 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 node

Each 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 the list loops forever.

5Try it

For a list of n nodes, how deep does the call stack get at most?

Show the answer

The answer is C. The function is called once per node, and no call finishes until the last node (the ) is reached. So at the deepest point n frames sit together and the extra memory is .

Which node does each call return?

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.