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?
Correct : b
The function counts nodes in a non-empty singly linked list recursively. The base case must identify when we are at the last node, and the recursive case must move forward through the list.
Option A — Wrong
E1 checks head==NULL which would never be true on first call since the list is non-empty. E2 passes head again instead of head->next, causing infinite recursion with no progress through the list.
Option B — Correct
E1 checks head->next==NULL — this correctly identifies the last node in the list. When we reach the last node, we return 1 to count it. E2 returns 1 + getListSize(head->next) — this counts the current node as 1 and recursively counts the rest of the list. The recursion advances through the list with head->next and terminates when the last node is reached.
Option C — Wrong
E1 checks head==NULL and returns 1 — but when head is NULL the list has ended and there are no more nodes to count. Returning 1 here would add an extra phantom node to the count, giving a result that is always one more than the actual size.
Option D — Wrong
E1 is the correct base case but E2 passes head instead of head->next. The function calls itself with the same node repeatedly, causing infinite recursion and a stack overflow.
Correct answer: B ✓
Similar Questions
Total Unique Visitors