IPA FE Subject B first sample Question 3
A question IPA Japan published in 基本情報技術者試験 科目Bのサンプル問題 問3, translated into English. ITPEC is based on the same exams.
From the answer group below, select the correct combination of answers to be inserted into A and B in the program.
The procedure append adds the character given as the argument to a singly linked list. Each element of the singly linked list is represented by the class ListElement. The figure shows the explanation of the class ListElement. ListElement-type variables store references to instances of the class ListElement. The global variable listHead stores a reference to the head element of the singly linked list. When the list is empty, listHead is undefined.
Figure Explanation of the class ListElement
Answer group
Explanation
A: undefined, B: curr — an empty list takes the new element as its head; otherwise the new element is linked after the last one.
curr is the new element: the constructor sets its val to qVal, and its next is undefined. When the list is empty, listHead is undefined and the new element becomes the head, so A is undefined. Otherwise prev starts at the head and the while loop moves it on until prev. is undefined, so it stops on the last element. Setting prev. links the new element after it, so B is curr; its own next is undefined, so it is the new tail.
Run from an empty list, appending “X”, “Y” and “Z” with (a) gives X → Y → Z.
Answer (a)
Why not others:
- •(b) —
curr.is undefined, so the last element'snext nextstays undefined and nothing after the first character is ever added - •(c) —
listHeadlinks the last element back to the head: the second call makes the head point to itself, and the third never leaves thewhileloop - •(d), (e) and (f) — with A as not undefined, an empty list goes to
else, whereprevis undefined andprev.cannot be read; a non-empty list would have its head replaced by the new element, losing the restnext
Key rule: To append to a singly linked list, set the head when the list is empty; otherwise walk to the element whose next is undefined and set that next to the new element.
Linked List · AI-written, may contain errors
This question comes from the past questions IPA Japan publishes, translated into English by ITPEC Practice. ITPEC Practice is an independent study tool and is not affiliated with IPA or ITPEC. See the original paper (PDF) or Report an issue.