I have a singly linked list and I want to reverse it without allocating a second list. I keep losing the tail of the list when I reassign the next pointer. What is the correct order of operations to walk the list and flip each pointer safely so that nothing gets dropped along the way?
How do I reverse a linked list in place?
The trick is to keep three pointers: previous, current, and next. Before you overwrite current.next, save it in the next variable. Then point current.next back at previous, advance previous to current, and advance current to the saved next node. Repeat until current is null and previous is your new head. This runs in linear time and constant extra space.
Worth adding: this same three pointer dance is the basis for reversing sublists and for the classic palindrome check on a linked list, so it is well worth committing the pattern to memory once you have understood it.