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

A linked list is formed from the objects of the class given below: class Node { double sal; Node…

Computer Science20232 marksProgram
A linked list is formed from the objects of the class given below:
class Node
{
    double sal;
    Node next;
}
Write an Algorithm OR a Method to add a node at the end of an existing linked list. The method declaration is as follows:
void addNode(Node ptr, double ss)

Answer

Answer

AI
// adds a node with value ss at the end of the existing list that starts at ptr
void addNode(Node ptr, double ss)
{
    Node temp = new Node();   // create the new node
    temp.sal = ss;
    temp.next = null;         // it will be the last node
    while (ptr.next != null)  // move to the last node
        ptr = ptr.next;
    ptr.next = temp;          // link the new node after the last node
}
Algorithm: 1. Create a new node temp; set temp.sal = ss and temp.next = null. 2. Starting from ptr, move ptr = ptr.next while ptr.next is not null, so ptr reaches the last node. 3. Set ptr.next = temp. 4. End. Tested: starting with a one-node list (1000.0), addNode(head, 2000.5) and addNode(head, 3000) gave the list 1000.0 2000.5 3000.0.
Data structures

From ISC 2023 Computer Science Paper 1, question 11(i).