The Gateway to Computer Science Excellence
+21 votes
1.5k 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.
in DS by Veteran (52.2k points)
edited by | 1.5k views

2 Answers

+37 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); 
by Veteran (425k points)
edited by
Is it correct?
0
very nice solution.
0
i got the answer arjun sir...bt pls explain wat about O(n) time
+1
CAn we take another stack for "a constant amount of additional storage"?
+1
@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..
+4
@abhishek14893

O(n) + O(n) + O(n) = O(n)
+1
but, what about the constant amount of additional storage mentioned in the question?? It will not be the another stack as if we take another stack then that will be dependent on the no. of elements in Q,which is not a constant amount of additional storage.
+1
We use given queue and stack each time..so no additional space is used.
+1 vote
The given requirement can be achieved by,

1.Transfer the n elements from queue  Q to  stack S. Now, elements present in stack is in reverse order. These step require n iterations.

2. Transfer the n elements present in stack to queue one by one using pop(S) operation.These step require n iterations.

3. Perform Step 1.

So total iteration = n+n+n = 3n = O(n).
by Active (2.3k points)

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,645 questions
56,551 answers
195,704 comments
101,558 users