How to implement a Stack using Queues in JavaScript

Yoon Hee Cho
2 min readDec 7, 2020
my favorite stack : pancake stack

Hello! Today, I worked on how to make a stack with queues. Queue has “First in First out”, but Stack has “Last in First out” rules. In order to make a Stack, I needed to make two queues. First, in Queue 1 array, I push data(elements) in order using .push() method. And then, while there are more than two elements in the Queue 1 array, I took out the first element in the Queue 1 and then push the element into the Queue2. When there is only one element left, which is the last element, I just return it. After return the last element, I took the first element in the Queue 2 array, and then push it to the Queue 1 to repeat the same process.

class StackFromQueues{
constructor(){
this.queue1 = [];
this.queue2 = [];
}

push(value){
this.queue1.push(value);
}
pop(){
//O(n) time
while(this.queue1.length > 1){
this.queue2.push(this.queue1.shift());
}
const value = this.queue1.shift();
//O(n) time
while(this.queue2.length){
this.queue1.push(this.queue2.shift());
}
return value;

//Time Complexity : O(n) + O(n) = O(2n) ~= O(n) time
//Space Complexity : O(n), but is required for the problem (2 queues)
}
}
const stack = new StackFromQueues();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
console.log('pop 4 off from the stack', stack.pop());
console.log('pop 3 off from the stack', stack.pop());
What is happening in the above code

--

--

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.