Welcome to linked list reversal. A linked list is a linear data structure where elements are stored in nodes. Each node contains data and a pointer to the next node. Our problem is to reverse the order of nodes so the last becomes first.
Now let's understand the algorithm. We use three pointers: prev initialized to null, current pointing to the head, and next for temporary storage. We iterate through the list while current is not null. In each iteration, we store the next node, reverse the current pointer, and move all pointers forward.
Let's trace through the algorithm step by step. Initially, prev is null and current points to the head. In each iteration, we reverse the pointer direction. After the first step, node 1 points to null. After the second step, node 2 points to node 1. Finally, node 3 points to node 2, and we have successfully reversed the entire list.
Here's the complete implementation. We define a ListNode class and the reverseList function. The algorithm has O(n) time complexity as we visit each node exactly once, and O(1) space complexity since we only use a constant amount of extra space. This technique is widely used in applications like undo functionality in text editors, browser back button history, and reversing data streams.
To summarize what we've learned: Linked list reversal is accomplished using three pointers to iterate through and reverse pointer directions. The algorithm achieves optimal O(n) time and O(1) space complexity. This fundamental technique has wide applications in software systems and forms the foundation for solving many advanced linked list problems.