Do you remember how recursion works? Well, then it is a very easy problem for you.
Now, in displayReverseHelper, if you look at the signature then you will find that a variable node of type Node is passed as parameter.
We use this function as our hidden function and code our main logic in this one.
We need to reach to the tail of the linked list so that while returning we can print the data of the present node, which gives us the elements of the Linked List in reverse order. So we simply make a call to displayReverseHelper(node.next) which takes us to the next node. This process will keep happening; means as soon as a call is made to node.next it will further make a call to node.next.next and so on.
There will come a point in Linked List when this call will be finally made to the tail of the Linked List. And then it will further make a call to its next which points to null, but we need to stop at tail only.
So in order to achieve so, we simply add a base case to the above code.
Yes! That looks complete.
But when a user uses this function in main, they don't know that they need to pass the head as an argument while calling the function displayReverseHelper(Node n).
This is where the use of second function displayRevrse() comes into action. In displayReverse(), we make a call to displayReverseHelper(head).
This is also the reason that displayReverseHelper() is a private function whereas displayReverse() is public so that users can only access the displayReverse().
Yes! That looks complete.
Let's consider a linked list of size 4 and its elements as: a b c d and look into the stack when displayReverse() is called.
What do you think will happen then?
Yes, a call to displayReverseHelper(head) will be made. That means that it will be added to stack, let's represent this call with the address of head in the stack.
Head will further make a call to the next element at 20k. And that to 30k and that to 40k. Now to notice, at 40k it is our last element that is the tail of the linked list.
When a further call will be made then the base case will hit.
After the base case is hit then functions start returning.
At first the control comes to 40k, then the print statement of this function will execute and d will be printed.
Then control will come to 30k and the print statement will execute and c will be printed.
Then control will come to 20k and 10k respectively and the print statement will execute and b and a will be printed in order.
That was easy. Wasn't it?