f you remember the previous question which was to display the reverse, then let me tell you that even here the reason to use two functions remains the same; reversePR() and reversePRHelper() .
Out of these both reversePR() is the public one, that is the one user can access and another reversePRHelper() is the private one in which we write our main code which is to change the pointers.
Inside reversePR(), we call reversePRHelper() and then add some other changes to it.
Inside reversePRHelper(), we make a recursive call, define a base case and do some self work.
Let's assume an example side by side; where a linked list is represented as follows. We call it Llist.
reversePRHelper(Node node)
- Since this is our main function therefore we will do our main part that is changing the pointers, inside this function. We will make use of recursion to do so, just like we did in our previous question.
- It is necessary that we start to change our pointers from the end so that our Linked List doesn't break in between and we therefore fail to complete the given task.
- So we reach to the last element making recursive calls to node.next each time.
- Base case will be hit when node.next becomes equal to null.
- When functions start returning, then we change node.next.next to node. This way if a is pointing towards b and b to null then b will now point to a.
- We start to make these changes from the last second element because we don't have access to tail.next.next as tail.next is null and null has nothing like next.
- These changes will be made till we reach the head. If a is the head and b head.next then after reversing, b points towards a but head i.e a still points towards b.
- So when reversePRHelper() is returned to reversePR() we further make some changes.
If we apply the above rules on Llist then it will look like shown below.
reversePR()
- When reversePRHelper() is returned to reversePR() we change the next head to null because after reversing the linked list, the original head becomes the tail.
- Finally we swap the head and the tail pointers using a temp Node.
Applying the above rules on Llist we get to see following changes which are final: