15% off all plans & roadmaps Use code
See plansReverse Linked List
- LeetCode 206
- Easy
- Linked List Manipulation Patterns
- In-place Reversal
Updated
TL;DR: Reverse a singly linked list by flipping each node's next pointer to point at the node before it. Walk the list once with a prev and a curr pointer and you finish in O(n) time and O(1) extra space.
Problem
Given the head of a singly linked list, reverse the order of its nodes and return the head of the reversed list.
Example 1
Input: head = [1,2,3,4,5] Output: [5,4,3,2,1]
Example 2
Input: head = [1,2] Output: [2,1]
Example 3
Input: head = [] Output: []
Constraints
- The number of nodes in the list is in the range
[0, 5000]. -5000 <= Node.val <= 5000
Constraints that matter
- The list has at most 5000 nodes, so any O(n) or even O(n log n) method is fast. The real question is how much extra memory you use, not whether you time out.
- The list can be empty (0 nodes). Your code must return null without touching
head.next. - Values range from -5000 to 5000, so there is no overflow risk. You never do arithmetic on values anyway, only pointer changes.
- A depth of 5000 matters for recursion. Python's default limit is 1000 frames, so a recursive Python answer needs a raised limit or it crashes on a full-size list.
- The list is singly linked, so each node knows only its successor. You cannot walk backward, which is why you must save the next node before you overwrite a pointer.
Hints
Hint 1
This is the in-place reversal pattern for linked lists.
Hint 2
Treat the list like an array.
Solution
Intuition
This is the in-place reversal pattern for linked lists. The values do not need to move. A list is defined by its next pointers, so reversing the list means reversing every pointer.
Picture dealing a deck of cards one at a time onto a second pile. The top card is curr, the pile is prev, and each move points that card's link at the pile.
The trap is that a singly linked node only knows its successor. If you set curr.next = prev first, you lose the only reference to the rest of the list. So each step has a fixed order: save the next node, flip the pointer, then move forward.
Picture two lists side by side. The first is the reversed part you have already built, headed by prev. The second is the untouched remainder, headed by curr. Each step takes the front node off the remainder and pushes it onto the front of the reversed part. When the remainder is empty, the reversed part is the answer.
The same move shows up in palindrome checks, reversing a sub-range, and reversing in groups of k. Learn it once and write it from memory.
Worked example
Input: head = [1000, -2000, 0, 5000, -5000, 123, -321] Output: [-321, 123, -5000, 5000, 0, -2000, 1000] Explanation: The list has seven nodes. After reversal the last node (-321) becomes the head and the first node (1000) becomes the tail, pointing at null. Every other node now points at the node that used to come before it.
Approach 1: Brute force: copy values to an array
Treat the list like an array. Walk it once and copy every value into an array. Walk it a second time from the head and overwrite each node's value with the array read from the back.
This works because you never touch a pointer. It is easy to get right, but it uses memory proportional to the list length, and it rewrites node values instead of reversing the structure. That misses the point of the problem and breaks if other code holds references to specific nodes.
Steps
- If the list is empty, the loops do nothing and you return
head(null). - Walk from
headto the end and append eachvalto an array. - Reset a pointer to
head. - Walk the array from the last index down to index 0.
- At each step, write the array value into the current node's
valand move to the next node. - Return
head.
Dry run
On [1000, -2000, 0, 5000, -5000, 123, -321]:
- Pass 1 builds the array
[1000, -2000, 0, 5000, -5000, 123, -321]. - Pass 2 reads the array from the back: -321, 123, -5000, 5000, 0, -2000, 1000.
- The nodes, in order, receive those values.
- The list now reads
[-321, 123, -5000, 5000, 0, -2000, 1000], which matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the number of nodes. The first pass visits each node once, and the second pass visits each node once, so total work is 2n steps, which is O(n). The array holds one integer per node, so extra space is n values, which is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
vals = []
cur = head
while cur:
vals.append(cur.val)
cur = cur.next
cur = head
# Read the saved values from the back and overwrite the nodes in order
for v in reversed(vals):
cur.val = v
cur = cur.next
return headJavaTested in our runner
import java.util.*;
class Solution {
public ListNode reverseList(ListNode head) {
List<Integer> vals = new ArrayList<>();
ListNode cur = head;
while (cur != null) {
vals.add(cur.val);
cur = cur.next;
}
cur = head;
// Overwrite each node with the saved values, last to first
for (int i = vals.size() - 1; i >= 0; i--) {
cur.val = vals.get(i);
cur = cur.next;
}
return head;
}
}C++Tested in our runner
class Solution {
public:
ListNode* reverseList(ListNode* head) {
vector<int> vals;
ListNode* cur = head;
while (cur != nullptr) {
vals.push_back(cur->val);
cur = cur->next;
}
cur = head;
// Overwrite each node with the saved values, last to first
for (int i = (int)vals.size() - 1; i >= 0; i--) {
cur->val = vals[i];
cur = cur->next;
}
return head;
}
};JavaScriptTested in our runner
var reverseList = function(head) {
const vals = [];
let cur = head;
while (cur !== null) {
vals.push(cur.val);
cur = cur.next;
}
cur = head;
// Overwrite each node with the saved values, last to first
for (let i = vals.length - 1; i >= 0; i--) {
cur.val = vals[i];
cur = cur.next;
}
return head;
};GoTested in our runner
func reverseList(head *ListNode) *ListNode {
vals := []int{}
for cur := head; cur != nil; cur = cur.Next {
vals = append(vals, cur.Val)
}
cur := head
// Overwrite each node with the saved values, last to first
for i := len(vals) - 1; i >= 0; i-- {
cur.Val = vals[i]
cur = cur.Next
}
return head
}C#Tested in our runner
public class Solution {
public ListNode reverseList(ListNode head) {
var vals = new List<int>();
ListNode cur = head;
while (cur != null) {
vals.Add(cur.val);
cur = cur.next;
}
cur = head;
// Overwrite each node with the saved values, last to first
for (int i = vals.Count - 1; i >= 0; i--) {
cur.val = vals[i];
cur = cur.next;
}
return head;
}
}Approach 2: Recursion
What's slow, or rather wasteful, in the array copy: it allocates a whole second structure and rewrites values, when the list already holds everything you need. The data is in the pointers.
The insight that fixes it: trust the recursion to reverse everything after the head, then fix up the head. If reverseList(head.next) returns the reversed tail, then head.next is still the node that is now the tail of that reversed part. Setting head.next.next = head appends the old head to the end, and head.next = null makes it the new tail.
Steps
- Base case: if
headis null orhead.nextis null, returnhead. - Recurse on
head.nextand store the result asnewHead. - Set
head.next.next = headso the node afterheadnow points back at it. - Set
head.next = nullso the old head ends the list and no cycle forms. - Return
newHead, the same node at every level of the unwinding.
Dry run
Use the example to see the unwinding. The rule is the same at every level.
On [1000, -2000, 0, 5000, -5000, 123, -321] the calls go down seven levels until the node -321 has no next. That node is returned as newHead and passes up unchanged.
- At 123:
123.next.next = 123makes -321 point to 123. Then123.next = null. List: -321 -> 123. - At -5000: -123's tail grows: 123 -> -5000. List: -321 -> 123 -> -5000.
- At 5000: List: -321 -> 123 -> -5000 -> 5000.
- At 0: List: ... -> 5000 -> 0.
- At -2000: List: ... -> 0 -> -2000.
- At 1000: List: ... -> -2000 -> 1000, and 1000.next is null.
The returned head is -321, giving [-321, 123, -5000, 5000, 0, -2000, 1000].
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the number of nodes. Each node is the argument of exactly one call, and each call does a constant number of pointer assignments, so time is O(n). The calls nest n levels deep before any return, so the call stack holds n frames and space is O(n). In Python you must raise the recursion limit above 5000 or a full-size list overflows the default limit of 1000.
PythonTested in our runner
import sys
from typing import List, Optional
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Depth can reach 5000, above Python's default limit of 1000
sys.setrecursionlimit(max(sys.getrecursionlimit(), 20000))
if head is None or head.next is None:
return head
new_head = self.reverseList(head.next)
head.next.next = head # the node after head now points back at it
head.next = None # old head becomes the tail
return new_headJavaTested in our runner
import java.util.*;
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head; // the node after head now points back at it
head.next = null; // old head becomes the tail
return newHead;
}
}C++Tested in our runner
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head; // the node after head now points back at it
head->next = nullptr; // old head becomes the tail
return newHead;
}
};JavaScriptTested in our runner
var reverseList = function(head) {
if (head === null || head.next === null) {
return head;
}
const newHead = reverseList(head.next);
head.next.next = head; // the node after head now points back at it
head.next = null; // old head becomes the tail
return newHead;
};GoTested in our runner
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
newHead := reverseList(head.Next)
head.Next.Next = head // the node after head now points back at it
head.Next = nil // old head becomes the tail
return newHead
}C#Tested in our runner
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head; // the node after head now points back at it
head.next = null; // old head becomes the tail
return newHead;
}
}
Solution pattern
In-place Reversal
Approach 3: Iterative pointer reversalOptimalIn-place Reversal
What's slow in the recursive version: it keeps one stack frame per node, so memory grows with the list. The frames only exist to remember which node to fix after the deeper call returns.
The insight that fixes it: do the fix on the way forward instead. Keep two pointers, prev (head of the reversed part, starting at null) and curr (head of the remaining part). At each node, save curr.next, point curr back at prev, then slide both pointers forward. Three local variables replace the whole stack.
Why it is correct. The loop keeps one invariant: prev heads a correctly reversed list of every node already processed, and curr heads the untouched rest. Saving curr.next before the flip means no node is ever cut off, so nothing is lost or visited twice. When curr is null, every node has moved onto the reversed part, so prev is the full answer.
Steps
- Set
prev = nullandcurr = head. - While
curris not null, savenxt = curr.next. - Flip the link:
curr.next = prev. - Advance
prev = curr. - Advance
curr = nxt. - When the loop ends,
curris null andprevis the last node processed. Returnprev.
Dry run
| Step | curr | nxt (saved) | prev after step | Reversed part so far |
|---|---|---|---|---|
| start | 1000 | null | empty | |
| 1 | 1000 | -2000 | 1000 | 1000 |
| 2 | -2000 | 0 | -2000 | -2000, 1000 |
| 3 | 0 | 5000 | 0 | 0, -2000, 1000 |
| 4 | 5000 | -5000 | 5000 | 5000, 0, -2000, 1000 |
| 5 | -5000 | 123 | -5000 | -5000, 5000, 0, -2000, 1000 |
| 6 | 123 | -321 | 123 | 123, -5000, 5000, 0, -2000, 1000 |
| 7 | -321 | null | -321 | -321, 123, -5000, 5000, 0, -2000, 1000 |
After step 7, curr becomes null and the loop stops. You return prev, the node -321, and the list reads [-321, 123, -5000, 5000, 0, -2000, 1000]. The first node, 1000, was given next = null in step 1, so the list ends cleanly.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the number of nodes. The loop runs once per node and each run does four constant-time assignments, so time is 4n operations, which is O(n). The only extra storage is three pointer variables (prev, curr, nxt), independent of n, so space is O(1). It also has no recursion, so list length cannot overflow the stack.
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
curr = head
while curr:
nxt = curr.next # save the rest of the list first
curr.next = prev # flip the pointer
prev = curr # grow the reversed part
curr = nxt # move to the next unprocessed node
return prevJavaTested in our runner
import java.util.*;
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nxt = curr.next; // save the rest of the list first
curr.next = prev; // flip the pointer
prev = curr; // grow the reversed part
curr = nxt; // move to the next unprocessed node
}
return prev;
}
}C++Tested in our runner
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* nxt = curr->next; // save the rest of the list first
curr->next = prev; // flip the pointer
prev = curr; // grow the reversed part
curr = nxt; // move to the next unprocessed node
}
return prev;
}
};JavaScriptTested in our runner
var reverseList = function(head) {
let prev = null;
let curr = head;
while (curr !== null) {
const nxt = curr.next; // save the rest of the list first
curr.next = prev; // flip the pointer
prev = curr; // grow the reversed part
curr = nxt; // move to the next unprocessed node
}
return prev;
};GoTested in our runner
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
curr := head
for curr != nil {
nxt := curr.Next // save the rest of the list first
curr.Next = prev // flip the pointer
prev = curr // grow the reversed part
curr = nxt // move to the next unprocessed node
}
return prev
}C#Tested in our runner
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nxt = curr.next; // save the rest of the list first
curr.next = prev; // flip the pointer
prev = curr; // grow the reversed part
curr = nxt; // move to the next unprocessed node
}
return prev;
}
}Common mistakes
- Writing
curr.next = prevbeforenxt = curr.next. You overwrite the only link to the rest of the list, so every later node becomes unreachable. Savenxtfirst, every time. - Returning
headinstead ofprev. After the loop,headis the old first node, which is now the tail withnext = null, so you return a one-node list. Returnprev. - Forgetting
head.next = Nonein the recursive version. The old head still points at the node that now points back at it, which creates a two-node cycle and an infinite loop when the result is read. - Looping with
while curr.nextinstead ofwhile curr. The last node is never flipped, and an empty list crashes onNone.next. Loop oncurritself. - Skipping the base case
head.next is Nonein the recursion. Without it,head.next.nextdereferences null on the last node and throws. Check bothheadandhead.next. - Running the recursive version in Python without raising the limit. A 5000-node list needs about 5000 frames, and the default limit of 1000 raises
RecursionError. Usesys.setrecursionlimitor switch to the iterative loop.
Edge cases
- Empty list
[]: return null. The loop never runs andprevis still null. - Single node
[7]: return the same node. Itsnextis already null, and the loop setsnext = prev = null. - Two nodes
[1, 2]: after one flip the result is[2, 1]. This catches a missingnext = nullon the old head. - Duplicate values
[3, 3, 3]: the output is the same values, but the nodes must be reordered. Reversing by pointers still works because you track nodes, not values. - Maximum size, 5000 nodes: the iterative loop runs 5000 times. A recursive Python solution needs a raised recursion limit.
- Negative and zero values such as
[0, -5000, 5000]: values do not affect the pointer logic. The output is[5000, -5000, 0].
Follow-ups interviewers ask
- Can you do it both iteratively and recursively?
- Yes. Iterative uses prev and curr and runs in O(n) time with O(1) space. Recursive reverses the tail first, then sets head.next.next = head and head.next = null, with O(n) time and O(n) stack space. I would ship the iterative one because depth does not grow with the list.
- How would you reverse only the nodes between positions left and right?
- Walk to the node just before position left, then run the same prev/curr loop for right - left + 1 nodes. Reconnect the reversed block to the node before it and to the node after it. A dummy node before the head handles the case where left is 1.
- How would you reverse the list in groups of k?
- Count k nodes ahead. If fewer than k remain, leave them alone. Otherwise reverse those k nodes with the iterative loop, attach the block to the previous group's tail, and repeat from the next unprocessed node. Total work is still O(n) with O(1) extra space.
Reverse Linked List FAQ
What is the time complexity of Reverse Linked List?
It is O(n), where n is the number of nodes. Each node is visited once and gets a constant number of pointer changes. The recursive and iterative solutions share this bound.
Why use in-place pointer reversal for Reverse Linked List?
A linked list is defined by its next pointers, so reversing those pointers reverses the list without moving any data. It needs no extra array or stack, which brings extra space down to O(1). It is also the building block for reversing a sub-range, k-groups and palindrome checks.
Can Reverse Linked List be solved in O(1) extra space?
Yes. The iterative version uses only prev, curr and a saved next pointer, so extra space does not depend on n. The recursive version cannot reach O(1), because each call stays on the stack until the end of the list is reached.
What is the space complexity of the recursive reverse linked list solution?
O(n). The recursion goes one call per node before any call returns, so the stack reaches depth n. For 5000 nodes that is 5000 frames.
Why is my reverse linked list in Python raising RecursionError?
Python's default recursion limit is 1000 and the list can have 5000 nodes. Either raise it with sys.setrecursionlimit or use the iterative loop, which has no depth issue. Java, C++ and Go handle 5000 frames without changes.
Why must I save the next node before changing curr.next?
In a singly linked list, curr.next is the only reference to the remaining nodes. If you overwrite it first, nothing points at the rest of the list and you cannot continue. Saving it in a temporary variable keeps the remainder reachable.
Asked at
See which companies ask this — Pro
Related problems
- Palindrome Linked List · same technique: In-place Reversal
- Remove Duplicates from Sorted List · same technique: In-place Reversal
- Reverse Linked List II · same technique: In-place Reversal
- Remove Duplicates from Sorted List II · same technique: In-place Reversal
- Reverse Nodes in k-Group · same technique: In-place Reversal
- Merge Two Sorted Lists · same pattern: Linked List Manipulation Patterns
- Intersection of Two Linked Lists · same pattern: Linked List Manipulation Patterns
- Minimum Index Sum of Two Lists · same pattern: Linked List Manipulation Patterns
- Add Two Numbers · same pattern: Linked List Manipulation Patterns
- Reorder List · same pattern: Linked List Manipulation Patterns