Skip to content

adding an implementation of a queue using 2 stacks #137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 6, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions Data Structures/Queue/QueueUsing2Stacks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// implementation of Queue using 2 stacks
// contribution made by hamza chabchoub for a university project

class Queue {
constructor () {
this.inputStack = []
this.outputStack = []
}

// Push item into the inputstack
enqueue (item) {
this.inputStack.push(item)
}

dequeue (item) {
// push all items to outputstack
this.outputStack = []
if (this.inputStack.length > 0) {
while (this.inputStack.length > 0) {
this.outputStack.push(this.inputStack.pop())
}
}
// display the top element of the outputstack
if (this.outputStack.length > 0) {
console.log(this.outputStack.pop())
// repush all the items to the inputstack
this.inputStack = []
while (this.outputStack.length > 0) {
this.inputStack.push(this.outputStack.pop())
}
}
}

// display elements of the inputstack
listIn () {
let i = 0
while (i < this.inputStack.length) {
console.log(this.inputStack[i])
i++
}
}

// display element of the outputstack
listOut () {
let i = 0
while (i < this.outputStack.length) {
console.log(this.outputStack[i])
i++
}
}
}

// testing

const queue = new Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(8)
queue.enqueue(9)

console.log(queue.dequeue())
// ans = 1
console.log(queue.dequeue())
// ans = 2