Worked solution from the Computational thinking and Problem-solving Paper 3 Advanced Theory booklet, Part 1 of 2.
Declare the constant, two integers and the array:
CONSTANT Capacity = 25 DECLARE BasePointer : INTEGER DECLARE TopPointer : INTEGER DECLARE Stack : ARRAY[1:25] OF REAL
Constant declared correctly [1]
Two INTEGER variables declared correctly [1]
Array of 25 REAL items declared correctly [1]
The stack is empty when TopPointer is below BasePointer. Take the top item, then lower TopPointer. The function returns a REAL.
FUNCTION Pop() RETURNS REAL
DECLARE Item : REAL
Item ← 0
IF TopPointer >= BasePointer THEN
Item ← Stack[TopPointer]
TopPointer ← TopPointer - 1
ELSE
OUTPUT "The stack is empty - error"
ENDIF
RETURN Item
ENDFUNCTIONRETURNS REAL added to the header [1]
IF TopPointer >= BasePointer THEN [1]
Item ← Stack[TopPointer] [1]
TopPointer ← TopPointer - 1 [1]
RETURN Item [1]
Write any two of these points:
A queue is FIFO (first in, first out) and a stack is LIFO (last in, first out) [1]
Both can change in size [1]
Other points that also score: a stack uses one end for push and pop, but a queue uses opposite ends to enqueue and dequeue (a stack has one moving pointer, a queue has two).
▶ Topic lesson
A lesson on this topic · by rjmcompsci. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.