Prashnikaप्रश्निका
Code
About
‹ Back to the paper

Question 11(i)

2 marks

Computer ScienceISC 2023 Computer Science Paper 1ProgramData structures

Answer the following.

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

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)
Open in the Linked list visualiser

Answer

Answer

// 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.