Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript Interview Question: Create a Queue using Stacks
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Create a Queue implementation using two stacks. Do not use an
* array inside the Queue class. Queue should implement add() and
* remove().
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
class Stack {
constructor() {
this.data = [];
}
push(record) {
this.data.push(record);
}
pop() {
return this.data.pop();
}
peek() {
return this.data[this.data.length - 1];
}
}
class Queue {
constructor() {
this.stackA = new Stack();
this.stackB = new Stack();
}
add(record) {
this.stackA.push(record);
}
remove() {
while (this.stackA.peek()) {
this.stackB.push(this.stackA.pop());
}
const returnValue = this.stackB.pop();
while (this.stackB.peek()) {
this.stackA.push(this.stackB.pop());
}
return returnValue;
}
}
// Test it
(() => {
let queue = new Queue();
queue.add('A');
queue.add('B');
queue.add('C');
console.log('remove 1', queue.remove());
console.log('remove 2', queue.remove());
console.log('remove 3', queue.remove());
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment