206 - Reverse Linked List
Friday, 18 September 2026
Walk the list once and flip every next pointer backwards, carrying prev and curr along and saving the next node before each rewire.
Problem
Given the head of a singly linked list, reverse the list and return the head of the reversed list.
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Input: head = [1,2]
Output: [2,1]
Input: head = []
Output: [] Constraints:
- The number of nodes in the list is in the range
[0, 5000] -5000 <= Node.val <= 5000
Follow-up: a linked list can be reversed either iteratively or recursively. Could you implement both?
Approach
Reversing the list means every next pointer has to point at the node before it instead of the one
after it. Keep two pointers: prev is the head of the part already reversed, and curr is the node
being flipped right now. Point curr->next at prev, then step both forward.
The one thing to be careful about is that curr->next is the only way to reach the rest of the
list, so once it is overwritten the tail is gone. Save it in temp first, then rewire. When curr runs off the end, prev is sitting on the old last node, which is the new head.
null 1 -> 2 -> 3 -> null
^ ^
prev curr
null <- 1 2 -> 3 -> null
^ ^
prev curr
null <- 1 <- 2 3 -> null
^ ^
prev curr
null <- 1 <- 2 <- 3 null
^ ^
prev curr class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while(curr) {
ListNode* temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
return prev;
}
}; - time:
O(n)- every node is visited once - space:
O(1)- three pointers, and the nodes themselves are reused