Given the head of a singly linked list, reverse the list, and return the reversed list. Do it in-place with O(1) extra space.
head = [1,2,3,4,5][5,4,3,2,1]head = [1,2][2,1]prev = null, curr = headcurr != nullnxt = curr.next (don't lose the rest of the list)curr.next = prevprev = curr, curr = nxtprev — the new head of the reversed list
At every step, everything behind curr is already a valid reversed sub-list whose new head is prev.
By saving nxt before clobbering curr.next, we never lose the forward chain.
When curr reaches null, the entire list has been reversed and prev points to the new head.
Pushing every value onto a stack and rebuilding uses O(n) extra space. We can just flip the arrows in place.
Keep three pointers: previous, current and next. Save next, then point current back at previous. Move previous and current one step forward, and repeat until current is null.
Save next, flip the arrow, then step forward. Previous ends up as the new head.
Run the animation above on your own input, or watch the 1:05 video explanation of Reverse Linked List with a dry run and Java code.