Given the head of a singly linked list, reverse the list and return the reversed list’s head. Each node contains a value and a pointer to the next node. The reversed list should have all the same nodes but with every link pointing in the opposite direction. If the list is empty, return null.
Example
head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
The original list 1 → 2 → 3 → 4 → 5 is reversed so that every link points in the opposite direction, producing 5 → 4 → 3 → 2 → 1.
Walk through the list one node at a time, flipping each pointer to point backward instead of forward. You need three variables: prev (starts as null), curr (starts at head), and next (saved before you overwrite curr's pointer). After each flip, advance prev and curr one step forward.
Why this works
Each node in a linked list points to the next node. To reverse the list, you just need to make every node point to the previous node instead. By walking through one node at a time and flipping pointers as you go, you reverse the entire chain in a single pass.
Step by step
- Initialize two pointers —
prevstarts at null (nothing before the head) andcurrstarts at the head. - Save the next node — before flipping
curr.next, storecurr.nextin a temp variable so you don’t lose the rest of the list. - Flip the pointer — set
curr.next = prevso this node now points backward. - Advance both pointers — move
prevtocurrandcurrto the saved next node, then repeat. - Return prev — when
currbecomes null,previs sitting on the last node you visited, which is the new head.
Time: O(n)
Space: O(1)
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next; // save next before we overwrite it
curr.next = prev; // flip the pointer backward
prev = curr;
curr = next;
}
return prev; // prev is the new head after full traversal
}
}
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next; // save next before we overwrite it
curr->next = prev; // flip the pointer backward
prev = curr;
curr = next;
}
return prev; // prev is the new head after full traversal
}
};
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
curr = head
while curr:
next_node = curr.next # save next before we overwrite it
curr.next = prev # flip the pointer backward
prev = curr # advance prev one step
curr = next_node
return prev # prev is the new head after full traversal