


We first store the references of the previous and next elements. We need to reverse the list in place by changing the references in a way that the next element points to the previous element. Our goal is to reverse the linked list with a given pointer to the head. Return the prev pointer as the new head of the reversed list.īased on the above, you can see how our linked list will be reversed with the help of the following diagram I built to make it easier for you to visualize: Set current equal to next(this step moves the current node forward).ģ.Set prev to current (this step moves the previous node forward).Set current.next equal to prev (we can now change next of current by reversing the link).Set next to current.next (we need to store the next node of current before changing).Iterate through all nodes to traverse the list as long as there is a node and do the followings at each iteration: next: This pointer will store the next node before its reference is changed and it is initially set to null.Ģ.current: This one will start at the head of the list and keep track of the node we are currently on.prev: This pointer will track the node previous to the current node and we will set it to null because a singly link list node does not have a reference to its previous node.Initialize three pointers prev, current, and next :.We can reverse a linked list iteratively or recursively, but we will only focus on explaining the iterative approach for today by following these steps: The head of the list will be given as an input. The problem above is asking us to write a method to reverse a singly linked list in place and return the new head of the reversed list.
