206. Reverse Linked List

An Interactive Visual Explainer

Idea By: Chetan Pachpande | Executed By: Gemini
Back to Home

Problem Description

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example:

Input: head = [1,2,3,4,5]\nOutput: [5,4,3,2,1]

Constraints:

  • The number of nodes in the list is in the range [0, 5000].
  • -5000 <= Node.val <= 5000

Complexity Analysis

Time Complexity: $O(N)$

We iterate through the $N$ elements of the list once.

Space Complexity: $O(1)$

We only use a few extra pointers, regardless of the list size.

Intuition

Reversing a singly linked list iteratively involves changing the next pointer of each node to point to its previous node. We need to keep track of three pointers:

  1. prev: This pointer tracks the node that was just processed. It starts as null.
  2. curr: This pointer points to the current node being processed. It starts at the head.
  3. temp: This temporary pointer is crucial to store the next node of curr *before* we modify curr.next, preventing us from losing the rest of the list.

The process repeats: save curr.next, point curr.next to prev, then advance prev to curr and curr to the saved next node.

Step-by-Step Code

Live Visualization & Controls

Linked List

Click "Run Visualization" to start

Algorithm State

prev: null
curr: null
temp: null

Execution Controls