GATE / CS ARCHIVE

SIMILAR QUESTIONS / DATA STRUCTURES

Implement queue operations using stack reversal

2 questions solved the same way, newest first. Back to Data Structures

How these are solved

Choose stack orientation, implement enqueue/dequeue by PUSH/POP and two REVERSE operations. Preserve original group: operation budgets are opposite, so not repeats.

2 marks · MCQ
Report issue

Stacks & Queues

Question 41, GATE 2014: A stack supports PUSH, POP, and REVERSE, which reverses its current element order. Which statement about implementing a queue is true? A impossible; B ENQUEUE takes one instruction and DEQUEUE two; C ENQUEUE takes three and DEQUEUE one; D both take one.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

1. Set up the reasoning. Choose and maintain an invariant: the queue's front is always at the stack top. Then removing the front is simply POP; a newly enqueued item must be placed at the bottom without disturbing the old order.

2. Derive the result. Keep the queue front at the stack top. ENQUEUE(x) performs REVERSE, PUSH(x), REVERSE, placing x at the bottom while preserving the previous order. DEQUEUE performs POP. Thus three and one instructions respectively, C. A single reversal followed by a pop would leave the remaining stack in the wrong orientation for an arbitrary future operation sequence.

3. Check the interpretation. REVERSE, PUSH, REVERSE inserts at the bottom and restores the invariant. Counting only the reversal and pop needed for one isolated removal ignores the orientation needed by later queue operations.

Original paper, page 40 · Answer key

Descriptive
Report issue

Implement queue with reversible stack

Stacks & Queues

Question 13(a), GATE 2000: A stack supports PUSH, POP and REVERSE, which reverses all its elements. Implement ENQUEUE with one operation and DEQUEUE with three.
Question 13(a), GATE 2000: A stack supports PUSH, POP and REVERSE, which reverses all its elements. Implement ENQUEUE with one operation and DEQUEUE with three.
Tap to enlarge
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.

Original paper, page 8