Skip to content

Instantly share code, notes, and snippets.

@AlexeiDarmin
Created November 17, 2018 17:45
Show Gist options
  • Save AlexeiDarmin/7d074f97514bd51933bbe03f08b63f0d to your computer and use it in GitHub Desktop.
Save AlexeiDarmin/7d074f97514bd51933bbe03f08b63f0d to your computer and use it in GitHub Desktop.
Implement a queue using two stacks
class MyNewQueue<T> {
mainStack: MyStack<T>
tempStack: MyStack<T>
constructor(value: T) {
this.mainStack = new MyStack()
this.tempStack = new MyStack()
this.mainStack.push(value)
}
enqueue(value: T) {
this.mainStack.push(value)
}
isEmpty() {
return this.mainStack.isEmpty()
}
dequeue() {
let node
while (!this.mainStack.isEmpty()) {
node = this.mainStack.pop()
this.tempStack.push(node.data)
}
const dequeuedNode = this.tempStack.pop()
while (!this.tempStack.isEmpty()) {
node = this.tempStack.pop()
this.mainStack.push(node.data)
}
return dequeuedNode
}
// peek() is similar to dequeue
}
const myQueue = new MyNewQueue(0)
myQueue.enqueue(1)
myQueue.enqueue(2)
myQueue.enqueue(3)
myQueue.enqueue(4)
myQueue.enqueue(5)
while (!myQueue.isEmpty()) {
console.log(myQueue.dequeue().data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment