GATE / CS ARCHIVE

GATE CSE 2000 / QUESTION 13(a)

Implement queue with reversible stack

Data Structures · Stacks & Queues · Full GATE CSE 2000 paper

GATE 2000, Q13(a) Descriptive
Report issue

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