How to Make a Queue using Two Stacks in JavaScript

Yoon Hee Cho
2 min readDec 6, 2020

Recently, I started to study one algorithm problem per a day. It is not easy to train my brain to come up with the most time and space efficient solution right away. I realized when I visualize and write/explain what each line of code is doing, it helps me to understand it better. This article is one of my effort of me trying to understand it better. In the beginning, it was quite stressful because of the feeling that my brain is like squeezed, but I got to know ways to enjoy my studying.

What is “Stack”?

Stack is literally a stack. It is like piling up the plates. It has a “Last In First Out(LIFO)” rule. It is one of abstract data type(ADT) and use arrays to store the data. It uses .push() and .pop() methods.

You can never get the bottom chip unless you pick the top chip up!

What is “Queue”?

Queue is like a line to checkout at the grocery store. It has a “First In First Out(FIFO)” rule. It is also one of abstract data type(ADT) and use arrays to store data. Array methods like .push() and .shift() can be used to implement the Queue.

So, How to make a Queue using Two Stacks?

In order to implement a Queue, when I push 1,2,3, I need to get 1 for the first time(Queue-First In First Out). If I push 1, 2, 3 into a stack(stack1), 3 will be out for the first time(Stack — Last In First Out). So, I need to push 3 into another stack(stack2) and same for 2 and 1. So in stack2, there are 3,2,1 in the array. Since 1 is the last element, I can return 1.

class QueueFromStacks {
constructor() {
this.stack1 = [];
this.stack2 = [];
}
enqueue(value) {
this.stack1.push(value);
}
dequeue() {
if(this.stack2.length === 0) {
while(this.stack1.length > 0){
this.stack2.push(this.stack1.pop());
}
}
return this.stack2.pop();
}
}
const queue = new QueueFromStacks();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
console.log(queue.dequeue());
what is happening in the code above

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Yoon Hee Cho
Yoon Hee Cho

Written by Yoon Hee Cho

0 Followers

Yoon is a full-stack developer & designer. She is currently studying algorithms everyday and working on expressing what she felt with creative coding.

No responses yet

Write a response