Implement a Stack Using Queues + Producer-Consumer
Problem
Two related tasks. First, implement a LIFO stack (push, pop, top, empty) using only standard queue operations (enqueue, dequeue, size, peek). Second, implement a thread-safe producer-consumer over a bounded buffer, where producers block when it is full and consumers block when it is empty.
Input / Output
- Stack: a sequence of push/pop/top/empty calls behaving as a LIFO.
- Producer-consumer: concurrent producer and consumer threads sharing a fixed-capacity buffer.
Constraints
- The stack may use one or two queues; decide whether push or pop carries the O(n) cost.
- The producer-consumer must be race-free — no lost or duplicated items, correct blocking.
Example
- Stack:
push(1); push(2); top() -> 2; pop() -> 2; pop() -> 1. - Producer-consumer: capacity-2 buffer; a third produce blocks until a consumer removes an item.
added …