Interview Question
Country: India
This works and is O(n) amortized.
Let us not talk about practicality in questions like "make stack using only one queue", which probably will never arise in real life, apart from testing problem solving abilities of a candidate in an interview.
Of course you need to keep track of the count when you have to do the cycle again (which is missing from above solution).
Basically you need to maintain the number of elements which can be popped by Deque. If that count goes to zero, you do the cycle.
Here is some (psuedo)code trying to use the above answers
class <T> Stack {
public push(T elem) {
_stack.Enqueue(elem);
}
public T pop() {
if (_stack.IsEmpty()) throw StackEmptyException;
if (numPushable == 0) {
int numToCycle = _stack.Count;
while (numToCycle > 0) {
T elem = _stack.Dequeu();
_stack.Enqueue(T);
_numPushable++;
numToCycle--;
}
}
_numPushable--;
return _stack.Dequeu();
}
private Queue<T> _stack;
private int _numPushable = 0;
}
Getting O(1) amortized is an open problem, even with two queues.
One solution is, on a pop, to reverse the Queue (by deque/enque multiple times), get the element which needs to be popped, then restore the queue back to the original queue state.
So push is O(1) but pop is O(n).
[link]lmgtfy.com/?q=careercup.com%3Aimplement+a+stack+with+single+queue[/link]
Try it before you post a question here
You don't get the point of this site, Richa.
What good does it do a candidate to post a question here, if they have already been through it in an interview and have failed to answer it?
The point of posting here is to let _other_ people know what kind of questions are being asked.
This site is just a repository of questions. People post the problems they were asked, not necessarily the problems they want the solution to, irrespective of whether a web-search gives the solution.
No Anon this website is very disorganized already. I propose a stack overflow kind of implementation.
The solution that I am about to suggest may not be very performant nor practical (in multi-threaded application, but let me know if it makes sense.
- NewCoderInTown April 19, 20121. If the Queue does not keep a count of its elements, add a count property.
2. For each Pop operation of the stack
- Perform the following (Count -1) times
- Dequeue() an element and then Enqueue() the same element
3. Dequeue the element and return it (It should the top of the stack).
Adding base conditions and error & boundary checking, this Queue should work like a stack.