From Queue To Stack

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


Inspiration .

1 2 3 This is not possible

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.

1 solution

Tom Verhoeff
Sep 5, 2016

A single Queue can be used as a Rolodex , by taking items out one by one and immediately putting them back in again. This allows you to cycle through all the elements, using one extra variable (of the item's type). Furthermore, it is necessary to know the number of items in the queue (either because it is a query offered by the queue data type, or by maintaining it in a separate integer variable). That way, you can cycle to any desired item in the queue for removal.

To implement a stack, its push operation would correspond to putting an item (at the end) in the queue, and its pop operation would correspond to rotating the queue until the last item put is at the front, and then taking that item out.

It would not be a very efficient implementation, because pop involves a number of operations proportional the the stack's size. Note that with one Priority Queue you could create a reasonably efficient stack.

I don't see any abstraction in your solution. And it's not efficient to implement as you mentioned it clearly.

The good way to do this problem is by using 2 queues. When we have a new element we push it in an empty queue then we pop all the elements from the used queue into the queue where we pushed the last element.

N S - 4 years, 8 months ago

I don't see any abstraction in your solution. And it's not efficient to implement as you mentioned it clearly.

The good way to do this problem is by using 2 queues. When we have a new element we push it in an empty queue then we pop all the elements in the used queue into the queue where we pushed the last element.

N S - 4 years, 8 months ago

You will need another queue to store the items you are taking out.. Since the queue data type has standard operations corresponding to it ( in terms of implementation in the language), two queues would definitely be required at the minimum.

Vaibhav Ojha - 4 years, 5 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...