Computer Sciences > GATE 2026 SET-1 > Linked Lists
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)

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

Let LIST be a datatype for an implementation of linked list defined as follows:typedef struct list {int data;struct list *next;} LIST;Suppose a program has crea...
#1405 NAT
A palindrome is a word that reads the same forwards and backwards. In a game of words, a player has the following two plates painted with letters. From...
#1 MCQ
Which number does not belong in the series below? 2, 5, 10, 17, 26, 37, 50, 64
#4 MCQ

Related Topics

recursive linked list size GATE 2026 GATE CS 2026 Set-1 Q45 getListSize linked list C GATE E1 E2 expressions linked list count nodes singly linked list recursive count C GATE programming C GATE 2026 head next NULL base case recursive GATE

Unique Visitor Count

Total Unique Visitors

Loading......