GATE / CS ARCHIVE

GATE CSE 1994 / QUESTION 26

Queue-to-stack transfer preserving front order

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

GATE 1994, Q26 5 marks · Descriptive
Report issue

Stacks & Queues

Question 26, GATE 1994: A queue Q contains n items and stack S is empty. Move all items into S so the original queue front is the stack top, with all remaining relative order preserved. Use only queue Delete/Insert and stack Push/Pop, O(n) time and O(1) extra storage.
Tap to enlarge
Answer & solution

Answer: Transfer Q→S, then S→Q, then Q→S; use three n-iteration loops. (no official key was published)

Use a single item variable x and a loop counter. First repeat n times: x:=Delete(Q); Push(S,x). Next repeat n times: x:=Pop(S); Insert(Q,x). Finally repeat n times: x:=Delete(Q); Push(S,x). Here Delete removes the queue front, Insert appends at its rear, Push adds at the stack top, and Pop removes the top. No direct indexing or knowledge of either implementation is needed.

Let the original queue, from front to rear, be q1,q2,…,qn. After the first pass Q is empty and S is qn,…,q2,q1 from top to bottom, because each successive pushed item covers the previous one. The second pass pops in that reversed order and enqueues it, producing Q front-to-rear qn,…,q2,q1 and leaving S empty. The third pass reverses that queue order once more on the stack, leaving S top-to-bottom q1,q2,…,qn, exactly as required, and Q empty.

There are six primitive operations per item across the three passes, hence 6n operations and O(n) time under the usual constant-time ADT operations. Only x and counters are additional storage. The originally supplied queue and stack are reused rather than allocating another container. Recursively popping and pushing could also reverse an order but would consume O(n) call-stack storage and would violate the additional-space condition. The empty case performs no operations and already meets the postcondition.

Original paper, page 7