Algo-Sim › Linked Lists

Reverse Linked List (Recursive)

Easy · Linked Lists · step through it in Java, Python and C++ on your own input

Reverse the rest of the list recursively, then hook the current node onto its tail. Uses O(n) call stack.

Problem

Reverse a singly linked list, this time recursively: reverse everything after the head, then attach the head to the end of that reversed part. Return the new head.

Constraints

Edge cases to test

Follow-up questions

Why set head.next = null?
Otherwise the old first node still points to the second, creating a two-node cycle at the new tail.
What is the space cost?
O(n) for the call stack; prefer the iterative version when the list may be long.

Solution

Java

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode newHead = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return newHead;
}

Python

def reverse_list(head):
    if not head or not head.next:
        return head
    new_head = reverse_list(head.next)
    head.next.next = head
    head.next = None
    return new_head

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    ListNode *reverseList(ListNode *head) {
        if (head == nullptr || head->next == nullptr)
            return head;
        ListNode *newHead = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;
        return newHead;
    }
};

More Linked Lists problems