GATE CSE
First time here? Checkout the FAQ!
x
+6 votes
353 views

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 (58.9k points)   | 353 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. 

Do

Delete an item from Q

Push the item to S

While (! empty Q); 

Do

Pop an item from S

Insert the item to Q

While (! empty S); 

Do

Delete an item from Q

Push the item to S

While (! empty Q); 

 

answered by Veteran (285k points)  
selected by
Is it correct?
very nice solution.
i got the answer arjun sir...bt pls explain wat about O(n) time


Top Users May 2017
  1. akash.dinkar12

    3338 Points

  2. pawan kumarln

    2108 Points

  3. Bikram

    1922 Points

  4. sh!va

    1682 Points

  5. Arjun

    1614 Points

  6. Devshree Dubey

    1272 Points

  7. Debashish Deka

    1208 Points

  8. Angkit

    1056 Points

  9. LeenSharma

    1018 Points

  10. Arnab Bhadra

    812 Points

Monthly Topper: Rs. 500 gift card
Top Users 2017 May 22 - 28
  1. Bikram

    1008 Points

  2. pawan kumarln

    734 Points

  3. Arnab Bhadra

    726 Points

  4. Arjun

    342 Points

  5. bharti

    328 Points


22,893 questions
29,196 answers
65,302 comments
27,695 users