ITPEC FE Subject B October 2024 Question 10
From the answer group below, select the correct answer to be inserted into blank in the program.
The procedure addNode adds a node to a singly-linked list at the position specified by the argument pos. The argument pos is a positive integer that is equal to or less than the (number of nodes + 1) in the list. The position at the top of the list is 1.
The class ListNode represents a node in a singly-linked list. The table summarizes an explanation of the member variables of the class ListNode. ListNode-type variables store references to instances of the class ListNode. A reference to the first node in the list is pre-stored in the global variable listHead.
Table Explanation of the member variables of the class ListNode
Answer group
Explanation
prev.next — once the new node has taken over prev's successor, prev must point to the new node.
The loop stops with prev at node pos - 1, the node just before the insertion point. Insertion then changes two references: newNode. keeps the rest of the list behind the new node, and prev. puts the new node after prev.
Example: for the list A → B → C, addNode( runs the loop once (i = 2), so prev is B; X's next becomes C and B's next becomes X, giving A → B → X → C.
Answer (e)
Why not others:
- •(a) — makes the new node the head: the example list becomes X → C, losing A and B
- •(b) —
listHead.is the right field only whennext posis 2; in the example it gives A → X → C, losing B - •(c) —
listHead.is also a fixed position, right only whennext. next posis 3; forpos2 it sets B's next to X while X's next is B, forming a loop - •(d) — assigns to the local variable
prevonly; no node'snextchanges, so the new node is never linked in - •(f) —
prev.is still the old successor C, so C's next becomes X while X's next is C: a loop, with B still pointing at Cnext
Key rule: To insert after a node, set the new node's next first and the predecessor's next second; assigning to a local reference variable never changes the list itself.
Linked List · AI-written, may contain errors
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.