1
2
3
4
5
[0][1][2][3][4]
Iterative · three pointers
▸1prev ← ∅; curr ← head2while curr:3 next ← curr.next // save the rest4 curr.next ← prev // flip the arrow5 prev ← curr; curr ← next6return prev // new head
state
- prev∅
- currhead (1)
Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.
Try one problemGiven the head of a singly linked list, reverse the list and return the new head.
▸1prev ← ∅; curr ← head2while curr:3 next ← curr.next // save the rest4 curr.next ← prev // flip the arrow5 prev ← curr; curr ← next6return prev // new head
line 1Reverse the list in place. Keep three pointers: prev (the part already reversed, starts at ∅), curr (the node we are flipping), and next (a temporary so we don’t lose the tail).