First time here? Checkout the FAQ!
+6 votes

A queue $Q$ containing $n$ items and an empty stack $S$ are given. It is required to transfer all the items from the queue to the stack, so that the item at the front of queue is on the TOP of the stack, and the order of all other items are preserved. Show how this can be done in $O(n)$ time using only a constant amount of additional storage. Note that the only operations which can be performed on the queue and stack are Delete, Insert, Push and Pop. Do not assume any implementation of the queue or stack.

asked in DS by Veteran (59.8k points)   | 396 views

1 Answer

+16 votes
Best answer

We can do this be first extracting items one by one from Q, and inserting them to S. After all items are done, S will contain the items in reverse order. Now, pop the elements from S and insert to Q. After this operation, items in Q will be in reverse order from the starting. Now, extract items from Q and push on to stack and we are done. 


Delete an item from Q

Push the item to S

While (! empty Q); 


Pop an item from S

Insert the item to Q

While (! empty S); 


Delete an item from Q

Push the item to S

While (! empty Q); 


answered by Veteran (288k points)  
selected by
Is it correct?
very nice solution.
i got the answer arjun pls explain wat about O(n) time
CAn we take another stack for "a constant amount of additional storage"?

Top Users Jul 2017
  1. Bikram

    3782 Points

  2. manu00x

    2464 Points

  3. Debashish Deka

    1832 Points

  4. joshi_nitish

    1494 Points

  5. Arnab Bhadra

    1096 Points

  6. Arjun

    1054 Points

  7. Hemant Parihar

    1050 Points

  8. Shubhanshu

    972 Points

  9. Ahwan

    876 Points

  10. akash.dinkar12

    642 Points

23,953 questions
30,895 answers
29,273 users