Skip to content

Instantly share code, notes, and snippets.

@GreggSetzer
Created June 22, 2018 19:01
Show Gist options
  • Save GreggSetzer/ba7fbcdf7462bf62ae759aba4fd15b1f to your computer and use it in GitHub Desktop.
Save GreggSetzer/ba7fbcdf7462bf62ae759aba4fd15b1f to your computer and use it in GitHub Desktop.
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