GATE CSE
First time here? Checkout the FAQ!
x
+9 votes
472 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 (64.6k points)   | 472 views

1 Answer

+19 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 (295k points)  
selected by
Is it correct?
very nice solution.
i got the answer arjun sir...bt pls explain wat about O(n) time
CAn we take another stack for "a constant amount of additional storage"?
@arjun sir we are reversing the queue and pushing onto stack so top of stack is front of original queue but rest of the elements of original queue are also reversed with above explanation.. but they asked " the item at the front of queue is on the TOP of the stack, and the order of all other items are preserved". please clarify sir..


Top Users Sep 2017
  1. Habibkhan

    7142 Points

  2. Warrior

    2640 Points

  3. Arjun

    2480 Points

  4. rishu_darkshadow

    2466 Points

  5. A_i_$_h

    2214 Points

  6. nikunj

    1980 Points

  7. manu00x

    1846 Points

  8. makhdoom ghaya

    1770 Points

  9. Bikram

    1744 Points

  10. SiddharthMahapatra

    1718 Points


26,133 questions
33,705 answers
79,886 comments
31,105 users