I have a little bit of idea how recursion works. The invocation and the different context regarding the variables that are provided by stack which is used to store the values returned by previous called function.
For example,
void Factorial(int n)
{
if(n==0) return 0;
else if(n==1) return 1;
else
{
return n*Factorial(n-1);
}
}
in this recursive function for computing the factorial of given number, I know that the first call for suppose the given n is 5, will be 5*Factorial(4*Factorial(3....so on till it reaches any of the base conditions)) then it will traverse back in the order summing up the value such as 1*2*3*4*5=240.
What I have failed to understand is this code to print the items of singly linked list in reverse order.
void ReversePrint(Node head) {
if(head==null)
{
return;
}
else
{
ReversePrint(head.next);
System.out.println(head.data);
}
}
As far as I know given there are finite number of elements in linked list function works like,
firstly, since the head is not null it will go to else condition and head will be equals to head.next until it goes to null. and then what?
I may not express my problem in exact words. Hope you will explain. Thanks in advance.
Adding some extra comments should help:
So - essentially -
Resulting in the list being printed backwards.