Thursday, September 7th
Reverse part of a linked list
Given a linked list and 2 positions left and right, reverse the linked list in between the 2 positions
We start the function by checking for an empty head
Next we declare 2 pointers, current and previous. Then we iterate over the list left-1 times, updating the previous pointer to current, and the current to the next node. The reason we iterate only left-1 times is because the list is indexed at 1
Before moving forward, we declare 2 pointers that will help connect the list together once the part of it is reversed. First is a pointer that will point from the beginning part of the list to the start of the reversed part.
We also declare a pointer that will connect the end of the reversed part of the list to the proper end of the list
Now we iterate over the number of nodes we need to reverse. First we declare a third pointer nextnode which points to the next node after current. Then within the for loop, we set next node equal to current next, set current next to the previous node (reversing it), then set previous to current, and current to the next node. We are using 3 pointers to move forward in the linked list while reversing it.
Once the part of the list is reversed, we connect it back with the original list.
If the start of the list pointer isn't null, we point the next node to the end of the reversed list. If it is null, it means that the reversal asked to head node, so set head equal to the end of the reversed list.
Finally, set the end of the reversed list to the current node, the start of the unsorted list's end
Return head
In an interview it would be important to ask if swapping values is acceptable. But prepare for the worst case. This problem demonstrates how to use 3 pointers for moving forward while reversing the list.
Thanks to the Editorial for demonstrating 2 interesting solutions
Comments
Post a Comment