Stack to queue

How many stacks are required to implement a queue if no other data structures such as arrays or linked lists are available?

1 2 This is not possible 4 3

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

3 solutions

This is a very interesting problem. Here is what you do.

Take two stacks, call one stack the loading stack and the other unloading.

To enqueue:

  1. Push the given thing on the loading stack.

To dequeue:

  1. First, check the unloading queue. If it's not empty, immediately pop from there. Otherwise, go to step 2.
  2. Pop the items in the loading stack and push them onto the unloading stack one-by-one. Repeat until the loading stack is empty.
  3. Pop the item at the top of the unloading stack and output.
N S
Oct 5, 2016

When we have a new element we push it into an empty stack then we pop all the elements from the used stack into the stack where we pushed the last element.

Owen Leong
Oct 31, 2015

Well, we can't really fully implement a queue since the time complexity of enqueuing or dequeuing will not be able to match that of a normal queue.

The first stack can be named temporary stack and the second queue stack. The queue stack will be the queue in stack form. The temporary stack will help in enqueuing.

My idea:

To enqueue:

Push all current elements in the queue stack into the temporary stack. Now push the element into the queue stack, then push all elements from the temporary stack back into the queue stack.

To dequeue:

Just pop the top element of the queue stack.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...