16. Reverse Linked List
Given the head of a singly linked list, reverse the list, and return the reversed list's head.
How It Works & Algorithmic Design
Solves using Three-Pointer Iterative Pointer Reversal:
- Pointers: Maintain
prev = null,curr = head, andnext = null. - Traversal Loop (While
curr !== null):- Save next node:
next = curr.next. - Reverse pointer direction:
curr.next = prev. - Shift pointers forward:
prev = curr,curr = next.
- Save next node:
- Return:
prevnow points to the new head of the reversed linked list.
Why This Approach Works Best
Reverses all link directions in a single pass ($O(n)$ time) without allocating extra nodes or array memory ($O(1)$ space).
Example Walkthrough
Input List:
1 -> 2 -> 3 -> 4 -> nullSingly linked list.
Pointer Reversal:
null <- 1 <- 2 <- 3 <- 4 (head=4)Pointers reversed in place.
Output Head:
4 -> 3 -> 2 -> 1 -> nullNew head node is 4.
Answer: Reverse linked list iteratively
function reverseList(head) {
let prev = null, curr = head;
while (curr !== null) {
const nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}💡 Reverse node references step by step using prev, curr, and next tracking pointers.
Key Takeaways
- Store
curr.nextbefore overwriting the node's pointer. - Iterative reversal works in $O(n)$ time and $O(1)$ space.
- Return
prevas the new head whencurrreachesnull.