How To Reverse A Linked List With Animated Examples
Understand the algorithm with gifs
The linked list reversal algorithm can be difficult to understand without visuals. So…here are some visuals. First we’ll show just the algorithm’s raw logic, and then we’ll sync the animation to the actual code.
Check out the newer version of this article with updated code: https://mostlyfocused.com/pages/articles/how_to_reverse_linked_list
What is a reversed linked list?
Reversing a list means taking each next
pointer and swapping it from the node to the right, to the node on the left.
Essentially the head becomes the tail and the tail becomes the head. To be extra clear I’m not talking about doubly linked lists in this article.
Flipping without orphaning
The trick to the algorithm is saving a reference to the next
node before we flip the pointer. If we flip the pointer too soon, we’d break the chain and have nowhere to jump for the next iteration of the loop.