Open In App

Data Structures | Linked List | Question 1

Like Article
Like
Save
Share
Report

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);
}

(A)

Prints all nodes of linked lists

(B)

Prints all nodes of linked list in reverse order

(C)

Prints alternate nodes of Linked List

(D)

Prints alternate nodes in reverse order


Answer: (B)

Explanation:

This function fun1 recursively prints the elements of a linked list in reverse order.

It first checks if the head is NULL, and if it is, it returns without doing anything. Otherwise, it calls the fun1 function recursively with the next node in the linked list (head->next). This continues until the last node is reached, which is the node whose next pointer is NULL.

At this point, the function starts returning, and as it returns it prints the value of each node in the linked list starting from the last node, working its way backwards to the first node. This is achieved through the printf statement which prints the value of head->data.

Thus, when this function is called with the head of a linked list as an argument, it will print the values of the nodes in reverse order.


Quiz of this Question
Please comment below if you find anything wrong in the above post


Last Updated : 05 Jan, 2013
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads