Consider the following C program. struct listnode { int data; struct listnode…
2021
Consider the following C program.
struct listnode
{
int data;
struct listnode *next;
};
void fun (struct listnode *head);
{
if(head == NULL || head → next == NULL) return;
struct listnode *tmp = head → next;
head → next = tmp → next;
free (tmp);
fun (head → next);
}What is the functionality of the above function?
- A.
It reverses the linked list
- B.
It deletes the linked list
- C.
Alternate nodes will be deleted
- D.
It reverses the linked list and deletes alternate nodes
- E.
Question not attempted
Attempted by 332 students.
Show answer & explanation
Correct answer: C
The function recursively removes every second node from the linked list. Step 1: If the list is empty or has only one node, the function returns without doing anything. Step 2: It stores the second node (head → next) in a temporary pointer tmp. Step 3: It updates the head's next pointer to skip the second node (head → next = tmp → next). Step 4: It frees the memory of the second node (free(tmp)). Step 5: It recursively calls itself on the new head (head → next), which is now the third node. This process continues, removing every second node in the list, leaving only the nodes at odd positions.