Created
June 22, 2018 19:01
-
-
Save GreggSetzer/ba7fbcdf7462bf62ae759aba4fd15b1f to your computer and use it in GitHub Desktop.
JavaScript Interview Question: Create a Queue using Stacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * | |
* 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