Check if number is a power of 2
June 12, 2012
camel & banana puzzle
June 12, 2012

Output of a C function

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).

2 Comments

  1. Baahu says:

    Input in the example provided is incorrect.

Leave a Reply to Commenter 642 Cancel reply

Your email address will not be published. Required fields are marked *