What does it solve?
Turn 1→2→3→4→∅ into 4→3→2→1→∅, reusing the same nodes. No new list, no array copy: just redirect each node's pointer to face backward.
Key insight: walk the list with three references. prev starts null, curr at the head. Each step: stash next = curr.next (so you don't lose the rest), flip curr.next = prev, then slide both forward (prev = curr, curr = next). The order matters: save next before flipping, or you strand the remaining nodes. When curr hits null, prev is the new head.
The core idea
prev = null, curr = head
while curr:
next = curr.next // save
curr.next = prev // flip
prev = curr // advance
curr = next
return prev
Complexity
Each node is visited exactly once and its pointer flipped in constant time. A single pass over the list.
Three pointers, regardless of list length. In-place: the recursive version instead costs O(N) stack space.
Lists & edge cases
Step-by-step table
| Step | Sub-op | prev | curr | next | List so far |
|---|
C++ implementation
#include <bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode* next; }; // Iterative reversal: flip each next pointer, walking prev/curr/next. ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; while (curr) { ListNode* next = curr->next; // save the rest first curr->next = prev; // flip the pointer backward prev = curr; // advance prev curr = next; // advance curr } return prev; // prev is the new head }
My Notes