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
- 0 ≤ number of nodes ≤ 5000
- -5000 ≤ Node.val ≤ 5000
- The recursion is n calls deep, so it uses O(n) stack
Edge cases to test
- Empty list
- One node
- A very long list (stack depth)
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_headC++
#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
- Reverse Linked List (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)