Movatterモバイル変換


[0]ホーム

URL:


HappyCoders logo
Stack feature imageStack feature image
HappyCoders Glasses

Implementa Stack Using Queues

Sven Woltmann
Sven Woltmann
Last update: November 27, 2024
Sven WoltmannSven WoltmannMarch 16, 2022

The last part of this tutorial series was aboutimplementing a stack with a linked list. In this part, I'll show you how to implement a stack with a queue (or rather, with two queues).

This variant has hardly any practical use and is primarily used as an exercise (as a counterpart, I also have an exercise forimplementing a queue with stacks). Therefore: Maybe you want to try to find the solution yourself first!

As a reminder,a queue is a data structure where you insert elements on one side and take them out on the other – i.e., a first-in-first-out (FIFO) data structure.

How can we use this to implement a stack, that is, alast-in-first-out (LIFO) data structure?

The Solution – Step by Step

We insert the first element that we want to push onto the stack (in the example: "apple") into a queue. To remove it from the stack, we take it out of the queue again:

Inserting and removing an element from a queue

We cannot simply write the second element into this queue as well. That's because the queue works according to the FIFO principle. If we push "apple" and then "orange" into the queue, we also have to take "apple" out again first:

Inserting and removing two elements from a queue

In a stack, however, we mustfirst take out thelast element pushed onto the stack ("orange") – and not the first element inserted ("apple").

That is not possible with a single queue.

Instead, we proceed as follows when inserting an element:

  1. We create a new queue (shown in orange in the image below) and move the element to be inserted into it.
  2. We move the element from the first queue to the newly created queue.
  3. We replace the existing queue with the new queue.

The following image shows these three steps:

Pushing the second element onto the stack
Pushing the second element onto the stack

After that, the elements are in the queue in such a way that we can take out the last inserted element, "orange", first and then the first inserted element, "apple".

This works not only with two elements but with as many as you like. The following image shows how we move the third element, "pear", onto the stack. I've split the second step from the previous image into steps 2a and 2b here: We first move "orange" from the old queue to the new one, then "apple".

Pushing the third element onto the stack
Pushing the third element onto the stack

After that, we can take the elements out of the stack in last-in-first-out order, so first the last inserted "pear", then the "orange", then the first inserted "apple".

Source Code for the Stack with Queues

Below you can see that the source code for the solution is quite simple.

For the queue, I use the simplest queue implementation,ArrayDeque. The fact that it is also a deque doesn't bother us because we assign it to a variable whose type is theQueue interface.

You can find the source code in theQueueStack class in the GitHub repository.

publicclassQueueStack<E>implementsStack<E>{private Queue<E> queue =new ArrayDeque<>();@Overridepublicvoidpush(E element){    Queue<E> newQueue =new ArrayDeque<>();    newQueue.add(element);while (!queue.isEmpty()) {      newQueue.add(queue.remove());    }    queue = newQueue;  }@Overridepublic Epop(){return queue.remove();  }@Overridepublic Epeek(){return queue.element();  }@OverridepublicbooleanisEmpty(){return queue.isEmpty();  }}Code language:Java(java)

The demo programStackDemo shows you how to useQueueStack.

Outlook

In the next and last part of the tutorial, we'll cover another exercise:How to reverse a stack via recursion?

If you still have questions, please ask them via the comment function. Do you want to be informed about new tutorials and articles? Thenclick here to sign up for the HappyCoders.eu newsletter.

ShareTweetShareShare

About the Author

As aconsultant and trainer with over 20 years of experience, I support Java teams in building modern backends – with a focus on performance, scalability, and maintainability.

I analyze bottlenecks, optimize existing systems, and share deep technical knowledge through hands-on, practical training.

More about me »Request consulting »Java trainings »

Leave a ReplyCancel reply

Your email address will not be published.Required fields are marked*

You might also like the following articles


[8]ページ先頭

©2009-2025 Movatter.jp