← DSA
EASY

Reverse Linked List

PracticeNeetCode ↗LeetCode ↗

Given the head of a singly linked list, reverse the list in place and return the new head.

Example

Input head = [1,2,3,4,5]
Output [5,4,3,2,1]

Key Pointers

Step-by-Step Analysis

  1. Initialize prev = None, curr = head.
  2. While curr is not None: save next_node = curr.next.
  3. Point curr.next = prev, then advance prev = curr, curr = next_node.
  4. When curr is None, prev is the new head — return it.

Complexity

Time: O(n) — Space: O(1)

Code

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverseList(head: ListNode | None) -> ListNode | None:
    prev = None
    curr = head
    while curr:
        next_node = curr.next
        curr.next = prev
        prev = curr
        curr = next_node
    return prev

Code Explanation

How the solution above works, piece by piece.

  1. prev = None: the reversed part starts empty (the old head will end up pointing to None).
  2. next_node = curr.next: save the rest of the list before changing any pointer, or it would be lost.
  3. curr.next = prev: flip this node to point backwards.
  4. prev = curr, curr = next_node: step both pointers forward.
  5. When curr is None, prev is the old tail, which is the new head. O(n) time, O(1) space.

Visual Walkthrough

Running it on head = [1, 2, 3, 4, 5]:

Reversing 1 to 5, one node per loopstart: prev = NoneNone12345Nonecurrafter loop 11Noneprev2345Nonecurrafter loop 221Noneprev345Nonecurrafter loop 3321Noneprev45Nonecurrafter loop 44321Noneprev5Nonecurrafter loop 5 → return prev54321Noneprev
Left chain: the part already reversed, headed by prev. Right chain: the part not reached yet, headed by curr. Each loop moves one node from the right chain to the front of the left chain.
prevcurr

Video Explanation

NeetCode — Reverse Linked List, LeetCode 206