ITPEC FE Subject B April 2024 Question 10
From the answer group below, select the correct combination of answers to be inserted into A and B in the program.
The procedure Insert inserts an integer number given by the argument after the last element of the linear circular linked list. Each element of the linear circular linked list is represented by the class ListElement. The figure shows the description of the class ListElement. The ListElement-type variable holds a reference to an instance of the class ListElement. The global variable listHead holds a reference to the head element of the linear circular linked list. Remember that in the circular linked list the last element points to the listHead. Here, if the list is empty, listHead is set to undefined.
Figure Class ListElement
Answer group
Explanation
A: listHead, B: tmp.next — walk from the head to the node whose next leads back to the head; that node is the last element.
- •In a circular list the last element's
nextislistHead, so the loop moves on whiletmp.is notnext listHead: A islistHead. - •Moving on means following the link: B is
tmp..next - •After the loop
tmpis the last element.tmp.hangs the new node after it, andnext ← newNode newNode.closes the circle again.next ← listHead
Trace: the list is 5 → 7 → back to 5, and 9 is inserted. tmp starts at 5, whose next is 7, not the head, so tmp moves to 7. The next of 7 is the head, so the loop stops. Then 7 links to 9 and 9 links to 5, giving 5 → 7 → 9 → back to 5.
Answer (b)
Why not others:
- •(a) —
newNodeis not in the list yet, sotmp.never equals it, andnext tmp ← listHead.sets the same node on every pass: the loop never endsnext - •(c) —
tmp ← listHeadputstmpback at the head on every pass, and the head'snextis never the head itself once there are two elements, so the loop never ends - •(d) —
newNode.has not been set yet, so with two or more elementsnext tmpbecomes undefined and the nexttmp.test failsnext
Key rule: To reach the tail of a circular list, stop at the node whose next is the head and advance with tmp ← tmp.; a loop whose variable never moves along the list cannot terminate.
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.