PRASHNIKAप्रश्निका
Back to the paper

A linked list is formed from the objects of the class Node. The class structure of the Node is…

Computer Science20192 marksShort answer
A linked list is formed from the objects of the class Node. The class structure of the Node is given below:
class Node
{
    int num;
    Node next;
}
Write an Algorithm OR a Method to find and display the sum of even integers from an existing linked list. The method declaration is as follows: `void SumEvenNode( Node str )`

Answer

Answer

AI
Algorithm: Step 1: Start. Set a temporary pointer temp = str (the head of the list) and sum = 0. Step 2: Repeat step 3 while temp is not null. Step 3: If temp.num is even (temp.num % 2 == 0), add it to sum (sum = sum + temp.num). Move temp to temp.next. Step 4: When temp becomes null (end of list reached), display the value of sum. Step 5: Stop. Method:
void SumEvenNode(Node str)
{
    int sum = 0;
    Node temp = str;
    while (temp != null)
    {
        if (temp.num % 2 == 0)
            sum = sum + temp.num;
        temp = temp.next;
    }
    System.out.println("Sum of even integers = " + sum);
}
(Verified by running the code: for a list 3->4->7->10->5, the method correctly printed "Sum of even integers = 14", i.e. 4+10.)
Data structures

From ISC 2019 Computer Science Paper 1, question 12(a).