A Two Stack Queue
Building a queue from two stacks in JavaScript
Initially, the idea of building a queue from two stacks made no sense to me. Why would you use two collections to create one collection? But as I explored the toy problem, and considered the challenge of queues in JavaScript, it all made so much sense.
First, let’s get the basics of the stack and the queue out of the way. Both of these collections are related to each other by being either first in, first out (FIFO) or first in, last out (FILO). Stacks, like a pile of dishes, are first in, last out. You’re gonna have to wash all those other dishes first before you are going to get to that first dish. Queues, on the other hand, are FIFO — like a line, the first in is going to be the first out.
In a stack, items are stored with a key that relates to its position in the stack. Stacks have methods that are similar to an array, we can pop the top item off, and we can push a new item onto the top of the stack. We can’t pull from anywhere else in the stack.
With a queue, we can add to the end of the line, and remove from the front of the line. Native JavaScript collections, arrays and objects, don’t come out of the box with a way to navigate a queue easily — we would have to completely rearrange an array every time an item leaves the queue. But if we make it with two stacks, and build some methods to use these two stacks behind the scenes, managing a queue becomes quite simple.
Let’s get into the code:
First, we initialize the Queue class with two instances of a Stack, one for the inbox and one for the outbox:
We will need three methods to navigate our queue: an enqueue (to add items), a dequeue (to remove items), and one to get the size of the queue.
Get Kris Mason’s stories in your inbox
Join Medium for free to get updates from this writer.
The enqueue is the most simple — let’s use the stack’s push method to add the item to the inbox:
It’s in the dequeue method that things get interesting. In order to simplify the process of getting to the front of the line and pulling that item out, each call to dequeue is actually going to pull the first item from the inbox, from the end of the outbox. If the outbox is empty, it will move all the items from the inbox to the outbox in reverse, and then pop the last item from the outbox.
Both of these methods rely on a size method that will track the total size of the queue. It’s a simple one, just add up the sizes of both inbox and outbox at any given moment:
While this is using prototype methods for a Stack class that builds the stack inside an object, this could also be build with an array, using the array’s prototype methods: pop and push. The size method would need to return the length of the inbox and outbox, but everything else would work just the same.
This was a fun puzzle to put together, and now that I’m on the other side of it, I can’t think of an easier way to build a queue.





