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

Question 11(i)

2 marks

Computer ScienceISC 2023 Specimen Computer Science Paper 1ProgramData structures

Write the program described below.

A linked list is formed from the objects of the class: class Node { int num; Node next; } Write an…

A linked list is formed from the objects of the class:
class Node
{
    int num;
    Node next;
}
Write an Algorithm OR a Method to insert a node at the beginning of an existing linked list. The method declaration is as follows:
void InsertNode( Nodes  starPtr, int n )
Open in the Linked list visualiser

Answer

Answer

Assuming a class-level Node reference start holds the head of the linked list, and startPtr is the current head passed into the method:
void InsertNode(Node startPtr, int n)
{
    Node temp = new Node();
    temp.num = n;
    temp.next = startPtr;
    start = temp;
}
A new node temp is created and its data field is set to n; its next is made to point to the current first node (startPtr), and the class-level head pointer start is then updated to this new node, thereby inserting it at the beginning of the list.