Given the head of a singly linked list, reverse the list, and return the reversed list.
Approach & Solution
We reverse a linked list by keeping track of two pointers: prev
(the previous node) and curr
(the current node). At each step, we:
Save the next node so we don’t lose track of the list.
Reverse the current node’s pointer to point to prev.
Move
prev
forward tocurr
.Move
curr
forward to the saved next node.
We continue until curr
is null, meaning we’ve processed all nodes. At that point, prev will be the new head of the reversed list.
Code
ListNode ReverseList(ListNode head)
{
ListNode prev = null;
ListNode curr = head;
while (curr != null)
{
ListNode nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
}
return prev; // new head
}
Top comments (0)