15% off all plans & roadmaps Use code

See plans

Reverse Linked List

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.

View on LeetCode

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.

Watch the pattern animation

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

  1. If the list is empty, the loops do nothing and you return head (null).
  2. Walk from head to the end and append each val to an array.
  3. Reset a pointer to head.
  4. Walk the array from the last index down to index 0.
  5. At each step, write the array value into the current node's val and move to the next node.
  6. 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

TimeO(n)
SpaceO(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 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

  1. Base case: if head is null or head.next is null, return head.
  2. Recurse on head.next and store the result as newHead.
  3. Set head.next.next = head so the node after head now points back at it.
  4. Set head.next = null so the old head ends the list and no cycle forms.
  5. 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 = 123 makes -321 point to 123. Then 123.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

TimeO(n)
SpaceO(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_head
In-place Reversal pattern infographic for Reverse Linked List

Solution pattern

In-place Reversal

Part of Linked List Manipulation Patterns

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

  1. Set prev = null and curr = head.
  2. While curr is not null, save nxt = curr.next.
  3. Flip the link: curr.next = prev.
  4. Advance prev = curr.
  5. Advance curr = nxt.
  6. When the loop ends, curr is null and prev is the last node processed. Return prev.

Dry run

Stepcurrnxt (saved)prev after stepReversed part so far
start1000nullempty
11000-200010001000
2-20000-2000-2000, 1000
30500000, -2000, 1000
45000-500050005000, 0, -2000, 1000
5-5000123-5000-5000, 5000, 0, -2000, 1000
6123-321123123, -5000, 5000, 0, -2000, 1000
7-321null-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

TimeO(n)
SpaceO(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 prev

Common mistakes

  • Writing curr.next = prev before nxt = curr.next. You overwrite the only link to the rest of the list, so every later node becomes unreachable. Save nxt first, every time.
  • Returning head instead of prev. After the loop, head is the old first node, which is now the tail with next = null, so you return a one-node list. Return prev.
  • Forgetting head.next = None in 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.next instead of while curr. The last node is never flipped, and an empty list crashes on None.next. Loop on curr itself.
  • Skipping the base case head.next is None in the recursion. Without it, head.next.next dereferences null on the last node and throws. Check both head and head.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. Use sys.setrecursionlimit or switch to the iterative loop.

Edge cases

  • Empty list []: return null. The loop never runs and prev is still null.
  • Single node [7]: return the same node. Its next is already null, and the loop sets next = prev = null.
  • Two nodes [1, 2]: after one flip the result is [2, 1]. This catches a missing next = null on 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

Practise it