‹ Back to the paper
Question 12(a)
2 marks
Computer ScienceISC 2020 Computer Science Paper 1ProgramData structures
Write the program described below.
A linked list is formed from the objects of the class Node. The class structure of the Node is…
A linked list is formed from the objects of the class Node. The class structure of the Node is given below:
class Node
{
int n;
Node next;
}
Write an Algorithm OR a Method to find the product of the integer numbers from an existing linked list.
The method declaration is as follows:
void Product_Node( Node str )Answer
Answer
void Product_Node(Node str)
{
if (str == null)
{
System.out.println("The list is empty");
return;
}
int p = 1;
Node t = str;
while (t != null)
{
p = p * t.n;
t = t.next;
}
System.out.println("Product = " + p);
}Explanation: p starts at 1 and a temporary reference t starts at the first node str. The loop multiplies p by the number stored in each node (t.n) and moves t to the next node until t becomes null, i.e. the end of the list. The product is then displayed. Tested: for the list 2, 3, 7 the output is Product = 42.