Facebook Interview Question: Implement stack using a queue... | Glassdoor

Interview Question

Software Engineer Interview

Implement stack using a queue


Interview Answer

3 Answers


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

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

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.