Programming Basics (Pseudocode Tracing)
The following program inserts "F", in val[6], right after "C" (index 3) in the linked list A → C → E → D → B, linked by the array next, and then outputs the list from the element at index 1. Array indices start at 1. A next value of 0 marks the end of the list. What should replace 【a】 so that the output is A, C, F, E, D, B?
string array: val ← {"A", "B", "C", "D", "E", "F"}
integer array: next ← {3, 0, 5, 2, 4, 0}
【a】
integer: p ← 1
while (p ≠ 0)
output val[p]
p ← next[p]
endwhile
- Anext[3] ← 6, then next[6] ← next[3]
- Bnext[6] ← 3, then next[3] ← next[6]
- Cnext[6] ← next[3], then next[3] ← 6
Show answer and explanation
Answer: C. next[6] ← next[3], then next[3] ← 6
To insert, first make the new element F point to E, which C pointed to (next[3] = 5), and then make C point to F. next[6] ← next[3] gives next[6] = 5, and the following next[3] ← 6 links C → F → E. In the opposite order, next[6] ← next[3] runs after next[3] has become 6, so next[6] = 6: F points to itself and the output C, F, F, … never ends. When relinking a linked list, assign in an order that never loses the path to the following elements.
- A. next[6] becomes 6, so F points to itself and the traversal never ends.
- B. This gives next[6] = 3 and next[3] = 3, so C points to itself and the output A, C, C, … never ends.
- C. Correct. F is linked to E first, then C is linked to F.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions