ITPEC FE Morning October 2019 Question 6

Two stack operations are defined:

PUSH n: Pushes a data (integer value n) to the stack.

POP: Pops a data from the stack.

For an empty stack, which of the following is the result of performing stack operations in the sequence below?

PUSH 1 → PUSH 5 → POP → PUSH 7 → PUSH 6 →

PUSH 4 → POP → POP → PUSH 3

Explanation

3 on top, then 7, then 1 at the bottom — trace the operations; POP always removes the value pushed most recently.

Stack contents, bottom to top:

  • •PUSH 1, PUSH 5 → 1, 5
  • •POP removes 5 → 1
  • •PUSH 7, PUSH 6, PUSH 4 → 1, 7, 6, 4
  • •POP, POP remove 4, then 6 → 1, 7
  • •PUSH 3 → 1, 7, 3

Answer (c)

Why not others:

  • •(a) — the right values drawn upside down, with 1 on top; 3 was pushed last, so it must be on top
  • •(b) — what a queue (first in, first out) would hold: each removal takes the oldest value, so 1, 5 and 7 leave and 6, 4, 3 remain, 3 newest
  • •(d) — the same queue contents, and also turned upside down

Key rule: A stack is last in, first out: each POP undoes the latest PUSH still on the stack. Removing the oldest value instead is a queue.

Algorithm and Programming · 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.