GATE / CS ARCHIVE

GATE CSE 2026 SET 1 / QUESTION 39

A terminating recursive list-size function

Programming in C · Recursion · Full GATE CSE 2026 Set 1 paper

GATE 2026 Set 1, Q39 2 marks · MCQ
Report issue

Recursion

Question 39, GATE 2026: For a nonempty singly linked list, getListSize(head) returns 1 if E1 is true and otherwise returns E2. Choose between base tests head==NULL or head->next==NULL, and recursive expressions 1+getListSize(head) or 1+getListSize(head->next).
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Givens and goal

For a nonempty singly linked list, getListSize(head) returns 1 if E1 is true and otherwise returns E2. Choose between base tests head==NULL or head->next==NULL, and recursive expressions 1+getListSize(head) or 1+getListSize(head->next).

Approach

Match the base return value 1 to a one-node list and ensure recursion moves to a strictly shorter suffix.

Step-by-step solution

1. The input list is nonempty, so the current head points to a node. A one-node list is recognized by a null next pointer, and its length is 1.
2. If a next node exists, the tail beginning there is also nonempty. The total length is one for the current node plus the recursively computed tail length. This supplies the base condition and recursive expression in B.
3. Induction proves correctness: length 1 returns 1; assuming the routine counts a tail of length n−1, the recursive case returns 1+(n−1)=n.
4. Passing the unchanged head recursively never decreases the problem size and does not terminate on longer lists. Using head==NULL as the base test while returning 1 gives an extra count for the empty suffix. These defects eliminate the other choices.

Assumption: As usual for a finite singly linked list, the chain is acyclic. The question's recursion would not terminate on a cyclic structure.

Trace for three nodes A→B→C→NULL: the call at C detects next==NULL and returns 1; the call at B returns 1+1=2; the call at A returns 1+2=3. With a head==NULL base returning 1, even a one-node input would instead return 1+1=2. With an unchanged-head recursive call, any list longer than one node recurses forever rather than reaching the last node.

Original paper, page 28 · Answer key