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 Science20172 marksProgram
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 count the nodes that contain only odd integers from an existing linked list and returns the count. The method declaration is as follows:
int CountOdd( Node startPtr )

Answer

Answer

AI
int CountOdd(Node startPtr)
{
    int count = 0;
    Node ptr = startPtr;
    while (ptr != null)
    {
        if (ptr.num % 2 != 0)
            count++;
        ptr = ptr.next;
    }
    return count;
}
Explanation: start at the first node, visit every node until ptr becomes null, add 1 to count whenever the value of num is odd (num % 2 != 0, which also works for negative numbers) and finally return count. Tested by running: the list 5, 8, -3, 12, 7 gives 3 and an empty list gives 0.
Data structures

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