EasyFlip every next pointer with three pointers: prev, curr, next.
Given the head of a singly linked list, reverse the list and return the new head.
Walkthrough
try:
Reverse the links one node at a time with three pointers: prev, curr, next.
prevcurrnext
1function reverseList(head) { 4 while (curr !== null) { 5 const next = curr.next;
prev = null
step 0 / 27
line 2
prev = null
prev will become the head of the reversed list. It starts as null (the new tail’s next).
Intuition
Reversing means every node’s next pointer should aim at the node that came BEFORE it instead of after.
Walk the list with curr, and keep prev = the node behind it. At each step, point curr.next back at prev.
The catch: overwriting curr.next destroys your only link to the rest of the list — so save next = curr.next FIRST.
Then shuffle everything forward: prev = curr, curr = next. When curr falls off the end, prev is sitting on the last node — the new head.
The algorithm
- 01Set prev = null and curr = head.
- 02While curr is not null: save next = curr.next.
- 03Point curr.next at prev (the flip).
- 04Advance prev = curr and curr = next.
- 05Return prev — the new head.
Reference implementation
1function reverseList(head) { 4 while (curr !== null) { 5 const next = curr.next; // save the rest of the list
6 curr.next = prev; // flip this link backward
7 prev = curr; // advance prev
8 curr = next; // advance curr
10 return prev; // prev is the new head
Complexity
Space
O(1) — only three pointers.