‹ Back to the paper
Question 12(a)
2 marks
Computer ScienceISC 2020 Specimen Computer Science Paper 1ProgramData structures
Write the program described below.
A linked list is formed from the objects of the class Node. The class structure of the Node is…
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 insert a node at the beginning of an existing linked list.
The method declaration is as follows:
void InsertNode( Node starPtr, int n )Answer
Answer
void InsertNode(Node starPtr, int n)
{
Node t = new Node();
t.num = n;
t.next = starPtr;
start = t;
}Explanation: starPtr is the reference to the first node of the existing list and start is the class-level reference that holds the head of the list (starPtr = start when the method is called). A new node t is created and the number n is stored in it. Its next reference is made to point to the old first node (starPtr), and start is then made to point to t, so the new node becomes the first node. This also works for an empty list (starPtr is null), where the new node becomes the only node. Tested: inserting 30, 20 and 10 in turn gives the list 10 20 30.