Given the following structure of Node of the Linked List:
struct Node{ int data; Node *link; };
What is the purpose of the below function
void myFun(Node* head) { if(NULL == head){ return; } printf("%d ", head->data); if(head->link != NULL ) myFun(head->link->link); printf("%d ", head->data); }
Solution:
It is a classical example of both head recursion and tail recursion happening in the same function. You may also want to see my previous post on ‘Recursive function to traverse a linked list‘.
The function will print the alternate nodes first from head to tail and then from tail to head. For example, if the list is as shown below:
1->2->3->4->5->6->7->8
Then the output will be
1 3 5 7 7 5 3 1
The first printf will be printed before the recursive call and the second printf will be printed when the recursive call will be returning (hence printing backward).
Input in the example provided is incorrect.
Baahu, I crosschecked the input and output.. Its fine.. For the given input (in the example) the output of function is as given above only..