Consider the following code snippet in C language that computes the number of…
2026
Consider the following code snippet in C language that computes the number of nodes in a non-empty singly linked list pointed to by the pointer variable head.
struct node{
int elt;
struct node *next;
};
int getListSize (struct node *head)
{
if( E1 ) return 1;
return E2;
}
Which one of the following options gives the correct replacements for the expressions E1 and E2?
- A.
E1: head == NULL
E2: 1 + getListSize(head)
- B.
E1: head->next == NULL
E2: 1 + getListSize(head->next)
- C.
E1: head == NULL
E2: 1 + getListSize(head->next)
- D.
E1: head->next == NULL
E2: 1 + getListSize(head)
Attempted by 82 students.
Show answer & explanation
Correct answer: B
The function counts nodes recursively. For the base case (E1), check if the current node is the last one by verifying head->next == NULL.
For the recursive step (E2), add 1 for the current node and recurse on the next pointer: 1 + getListSize(head->next).