Facebook

  www.facebook.com
  www.facebook.com

Interview Question

Software Engineer Interview

Implement stack using a queue

Tags:
algorithm
Answer

Interview Answer

3 Answers

0

You need two stacks. You push to stack A, and pop from stack B. When B is empty, you reverse A onto B.

Anonymous on Nov 19, 2010
1

I think the question is to implement a stack using a queue DS.
For every push(), enqueu() in the queue. Then dequeu() every element and enqueue() the same immediately until we reach the element which was recently enqueued.
This way we maintain the queue in the form expected by the stack (LIFO)

deveffort on Mar 30, 2011
0

deveffort, i guess you will have to maintain 2 queues. After the first dequeue, your queue will contain items that are needed for stack retrieval(LIFO). But any more items you want to add to this queue will mess it up unless you maintain another queue.
So retrievals are always from one queue and additions area always on a different queue.

Anonymous on Apr 28, 2011

Add Answers or Comments

To comment on this, Sign In or Sign Up.