Count the number of nodes in the linked list which is not empty? struct node { int value; struct node * next; } fun (node * head) { if (E1) return 1; else E2; }
Correct Answer :
E1: head → next == Null, E2: 1 + fun (head → next);
Solution :
The correct option is: E1: head → next == Null, E2: 1 + fun (head → next);
Let us analyze the structure of the recursive function and determine how to count the nodes of a non-empty linked list. The skeleton of the function is:
struct node {
int value;
struct node * next;
};
fun (node * head) {
if (E1) return 1;
else E2;
}
1. Determining the Base Case (E1):
Since the problem states that the linked list is not empty, the minimum number of nodes in the list is 1. The base case of the recursion should handle the smallest possible input, which is a list containing exactly one node. In a singly linked list, the last node (or a single-node list) is characterized by having its next pointer point to Null. Thus, the condition to check if we are at the last node is:
E1: head → next == Null
When this condition is met, the function correctly returns 1.
2. Determining the Recursive Step (E2):
If the current node is not the last node (i.e., head → next != Null), the total number of nodes starting from the current node is 1 (for the current node itself) plus the number of nodes in the remainder of the list. The remainder of the list begins at the next node, head → next. Therefore, the recursive step must call fun on head → next and add 1 to the result:
E2: return 1 + fun(head → next);
3. Illustrative Trace:
Consider a linked list with two nodes: [Node 1] → [Node 2] → Null.
- We call fun(Node 1). Since Node 1 → next is Node 2 (not Null), the base case E1 is false. We execute E2, which evaluates to:
1 + fun(Node 2)
- In the recursive call fun(Node 2), Node 2 → next is Null. The base case condition E1 (head → next == Null) is true, so it returns 1.
- Substituting this back into the original call, the final expression evaluates to:
This correctly yields a count of 2 nodes.
Access expert-curated educational resources and study materials—completely free.
Create, conduct, and manage professional online assessments with Mindyard. Perfect for teachers and institutes.
Copyright © 2026 Mindyard. All Rights Reserved.