Chapter 18: Problem 17
Give pseudocode that implements a queue using two stacks. The queue operations enqueue, dequeue, and empty must be implemented in terms of the \(p u s h, p o p,\) and empty stack operations.
Short Answer
Expert verified
Answer: A queue can be implemented using two stacks (input and output) by performing the following operations:
1. Enqueue: push the item onto the input stack.
2. Dequeue: if the output stack is empty, transfer elements from the input stack to the output stack by popping elements from the input stack and pushing them onto the output stack. Then, pop and return the top element from the output stack.
3. Empty: check if both input and output stacks are empty to determine if the queue is empty.