Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Let the variable list represents a pointer to the head of linked list of nodes,

ID: 3826486 • Letter: L

Question

Let the variable list represents a pointer to the head of linked list of nodes, called LinkedNode; where LinkedNode is defined as follows: class LinkedNode {int data; LinkedNode next; LinkedNode(int i) {data = i; next = null;}} A node temp must be inserted at the front of the list. (where temp is defined as: Linked Node temp = new LinkedNode(200)) Which of the following sets of codes best describes the situation. Select the one right response. I IV III II When inserting nodes in a linked list the best method of keeping a sorted list is the method of inserting at the back and the front.

Explanation / Answer

The correct option is option (D) II where II means

temp.next = list
list = temp

Description:

Here, you are supposed to insert the node at the first position, which is pointed by 'list'.

So, you need to make sure that once you insert that node, its next is the head node before insertion.

And every time the node is either inserted or removed, the returned thing is : 'list' we only know the head and the rest nodes are linked from it.

So, now let's do the insertion...

You are to insert a node at the first location which means its next will be the current first node (pointed by list) right...

So, perform temp.next = list first.

This means now the 'next' of temp is having the address of 'list' so if we change the value of 'list', the node pointed by it, its information is not lost.

So, now assign list = temp and return list.


For example, 6 ->10 -> 20 is the linked list values before inserting a temp node having value '3'.

Now, if you say something like 3 -> next = 6, it means it is known that from 3, where to go ? On node 6.


We are not changing the 'next' of 6 so it is still pointing to 10 so the rest of the list is remaining as it is, we are just adding a node ahead of the first node.

So, now 3 becomes our head node so it should be pointed by 'list' so I can assign it to 'list' so that the updated linked list can be referred.

This does not change anything in the rest of the list, it just adds a node ahead of every node, so only 2 changes are needed : assign its next = previous head and assign it as the new head node.


Do comment if there is any query. Thank you. :)