Reverse a Linked List (LeetCode 206) β Explained with Code and Diagrams
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
headof 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]:
| Step | cur.val | pre | cur.next update | Resulting Link |
| 1 | 1 | null | 1.next = null | 1 β null |
| 2 | 2 | 1 | 2.next = 1 | 2 β 1 β null |
| 3 | 3 | 2 | 3.next = 2 | 3 β 2 β 1 β null |
After the loop, we return pre which now points to the reversed list.
π Time and Space Complexity
| Metric | Complexity |
| Time | O(n) |
| Space | O(1) |
