Skip to content

Commit 4f0ed31

Browse files
hmizzitsvinayak
andauthored
adding an implementation of a queue using 2 stacks (#137)
* adding an implementation of a queue using 2 stacks * Update QueueUsing2Stacks.js Co-authored-by: vinayak <itssvinayak@gmail.com>
1 parent 0b7f149 commit 4f0ed31

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// implementation of Queue using 2 stacks
2+
// contribution made by hamza chabchoub for a university project
3+
4+
class Queue {
5+
constructor () {
6+
this.inputStack = []
7+
this.outputStack = []
8+
}
9+
10+
// Push item into the inputstack
11+
enqueue (item) {
12+
this.inputStack.push(item)
13+
}
14+
15+
dequeue (item) {
16+
// push all items to outputstack
17+
this.outputStack = []
18+
if (this.inputStack.length > 0) {
19+
while (this.inputStack.length > 0) {
20+
this.outputStack.push(this.inputStack.pop())
21+
}
22+
}
23+
// display the top element of the outputstack
24+
if (this.outputStack.length > 0) {
25+
console.log(this.outputStack.pop())
26+
// repush all the items to the inputstack
27+
this.inputStack = []
28+
while (this.outputStack.length > 0) {
29+
this.inputStack.push(this.outputStack.pop())
30+
}
31+
}
32+
}
33+
34+
// display elements of the inputstack
35+
listIn () {
36+
let i = 0
37+
while (i < this.inputStack.length) {
38+
console.log(this.inputStack[i])
39+
i++
40+
}
41+
}
42+
43+
// display element of the outputstack
44+
listOut () {
45+
let i = 0
46+
while (i < this.outputStack.length) {
47+
console.log(this.outputStack[i])
48+
i++
49+
}
50+
}
51+
}
52+
53+
// testing
54+
55+
const queue = new Queue()
56+
queue.enqueue(1)
57+
queue.enqueue(2)
58+
queue.enqueue(8)
59+
queue.enqueue(9)
60+
61+
console.log(queue.dequeue())
62+
// ans = 1
63+
console.log(queue.dequeue())
64+
// ans = 2

0 commit comments

Comments
 (0)