Skip to main content

Command Palette

Search for a command to run...

Reverse a Linked List (LeetCode 206) β€” Explained with Code and Diagrams

Published
β€’2 min read

Reversing a singly linked list is a classic problem that tests your understanding of pointers and in-place modifications. In this post, I’ll walk you through an iterative solution, explain the pointer logic, and visualize what’s happening under the hood.


🧠 Problem Statement

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

Example:

textCopyEditInput:  head = [1, 2, 3, 4, 5]
Output:        [5, 4, 3, 2, 1]

You must reverse the list in-place, without allocating a new list.


πŸ’‘ Core Idea

In a normal singly linked list, each node points to the next:

csharpCopyEdit1 β†’ 2 β†’ 3 β†’ 4 β†’ 5 β†’ null

We need to reverse the links, so it becomes:

csharpCopyEditnull ← 1 ← 2 ← 3 ← 4 ← 5

πŸ§ͺ Iterative Solution

βœ… Code (Java)

javaCopyEditclass Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;       // The previous node (starts as null)
        ListNode cur = head;       // The current node being processed
        ListNode temp = null;      // Temporary pointer to store next node

        while (cur != null) {
            temp = cur.next;       // Step 1: Save next node
            cur.next = pre;        // Step 2: Reverse current node's pointer
            pre = cur;             // Step 3: Move pre forward
            cur = temp;            // Step 4: Move cur forward
        }

        return pre;  // pre will be the new head of the reversed list
    }
}

πŸ” Visual Walkthrough

Let’s walk through the reversal of [1 β†’ 2 β†’ 3 β†’ null]:

Stepcur.valprecur.next updateResulting Link
11null1.next = null1 β†’ null
2212.next = 12 β†’ 1 β†’ null
3323.next = 23 β†’ 2 β†’ 1 β†’ null

After the loop, we return pre which now points to the reversed list.


πŸ“Š Time and Space Complexity

MetricComplexity
TimeO(n)
SpaceO(1)