‹ Back to the paper
Question 11(i)
2 marks
Computer ScienceISC 2025 Improvement Computer Science Paper 1ProgramData structures
Write the program described below.
A linked list is formed from the objects of class VotersList. The class structure is given below…
A linked list is formed from the objects of class VotersList. The class structure is given below.
class VotersList
{
int age;
VotersList link;
}Write an Algorithm OR a Method to count and return total number of nodes whose age >= 60.
The method prototype is as follows:
int countNodes(VotersList start)Answer
Answer
int countNodes(VotersList start)
{
if (start == null)
return 0;
else
{
if (start.age >= 60)
return 1 + countNodes(start.link);
else
return countNodes(start.link);
}
}Explanation: The method recursively traverses the linked list node by node using the link reference. At each node, if age is 60 or more it adds 1 to the count returned by the recursive call on the rest of the list (start.link); otherwise it simply returns the count from the rest of the list. The base case (start == null) returns 0 when the end of the list is reached. Tested with a 4-node list of ages {65, 45, 70, 30}, the method correctly returns 2 (the nodes with age 65 and 70).