Reverse the arrows of a linked list one node at a time by keeping track of the previous, current and next node. No extra list is needed.
Used for
cur = 1: now points to null
2 now points to 1
3 now points to 2
Before you flip node 2 to point backwards, what must you remember first?
Not quite. Once node 2 points backwards, nothing points at node 3 any more. Save it first (next = cur.next) or the rest of the list is lost.
Step 1 of 6
Goal: reverse 1 → 2 → 3 → 4 so it reads 4 → 3 → 2 → 1, without building a new list. We only flip each arrow, using two helpers: prev (the node behind) and cur (the node we are looking at).
Step 2 of 6
Flip the arrow of node 1 so it points at nothing (null). Then move both helpers one node forward.
Step 3 of 6
Node 2: flip its arrow to point back at 1, then move forward.
Step 4 of 6
Node 3: flip its arrow to point back at 2.
Step 5 of 6
Node 4: flip it to point at 3. cur steps off the end, so prev (4) is the new first node: 4 → 3 → 2 → 1. One pass and no extra list: this is in-place reversal.
Step 6 of 6
Your turn.
function reverseList(head) { let prev = null; while (head) { [head.next, prev, head] = [prev, head, head.next]; } return prev;}