Similar questions 1 more →
Stacks & Queues


Answer & solution
Answer: ENQUEUE(x): PUSH(x). DEQUEUE: REVERSE; x = POP(); REVERSE; return x. (no official key was published)
Maintain the queue front at the bottom of the stack and its rear at the top. If queue order is a,b,c (a oldest), the stack bottom-to-top is [a,b,c]. ENQUEUE(d) executes PUSH(d), producing [a,b,c,d], exactly the required FIFO order. To remove the oldest element, REVERSE changes the stack to [d,c,b,a], POP returns a, and the second REVERSE restores [b,c,d]. Thus the invariant is restored after each completed operation. The return statement is not an additional stack operation. On an empty queue, detect underflow rather than POP an absent item. The question counts interface operations, not their implementation costs: REVERSE may require linear time in an ordinary stack representation.