Iterative
Intuition
The iterative approach reverses the list in a single pass by maintaining three pointers: previous, current, and next. At each step we save the next node, point the current node backward to the previous node, then advance both previous and current forward by one position. When current reaches nil, previous points to the new head. This runs in O(n) time with O(1) extra space since we only reassign existing pointers.
Algorithm
- Initialize `prev` to null and `curr` to `head`.
- While `curr` is not null, save `curr.next` in a temporary variable `next`.
- Set `curr.next = prev` to reverse the pointer direction.
- Move `prev` to `curr` and `curr` to `next`.
- When the loop ends, `prev` is the new head of the reversed list. Return `prev`.
O(n)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}def reverseList(head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prevfunc reverseList(head *ListNode) *ListNode {
var prev *ListNode
curr := head
for curr != nil {
next := curr.Next
curr.Next = prev
prev = curr
curr = next
}
return prev
}