What does the following function do for a given Linked List with first node as…

2025

What does the following function do for a given Linked List with first node as head?

void fun1(struct node* head)
{
    if (head == NULL)
        return;
    fun1(head->next);
    printf("%d ", head->data);
}
  1. A.

    Prints all nodes of linked lists

  2. B.

    Prints all nodes of linked list in reverse order

  3. C.

    Prints alternate nodes of Linked List

  4. D.

    Prints alternate nodes in reverse order

Show answer & explanation

Correct answer: B

Concept:

In a recursive function, whether a statement is written before or after the recursive call decides its execution order. Any statement BEFORE the recursive call runs in the same order the calls are made (head to tail). Any statement AFTER the recursive call runs only once that deeper call has returned — during the call stack's 'unwinding' phase — so those statements execute in the reverse of the call order.

Application:

  1. fun1(head=1) checks head != NULL, then immediately calls fun1(2) — node 1's printf has NOT run yet.

  2. fun1(2) similarly calls fun1(3) before its own printf runs.

  3. This continues through fun1(3) -> fun1(4) -> fun1(5) -> fun1(NULL).

  4. fun1(NULL) hits head == NULL and returns immediately — this is the base case, and no call has printed anything yet.

  5. Control now unwinds back up the stack: fun1(5) resumes and executes its printf, printing 5.

  6. fun1(4) resumes next and prints 4, then fun1(3) prints 3, fun1(2) prints 2, and finally fun1(1) prints 1.

  7. The full printed sequence is 5 4 3 2 1.

Cross-check:

Each recursive call advances by exactly one node (head->next), so every node in the list is visited exactly once — none skipped — ruling out both 'alternate node' options. And since each node's printf is deferred until its own call unwinds, the output order is exactly reversed relative to the list's head-to-tail order, matching the option describing reverse-order printing of ALL nodes.

Explore the full course: Coding For Placement