Skip to content

Commit fa2a68a

Browse files
committed
update: queue using stack
1 parent d9355b9 commit fa2a68a

File tree

1 file changed

+28
-0
lines changed
  • src/_DataStructures_/Queue/queue-using-stack

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const Stack = require('../../Stack');
2+
3+
class Queue {
4+
constructor() {
5+
this.queue = new Stack();
6+
this.temp = new Stack();
7+
}
8+
9+
enqueue(data) {
10+
this.queue.push(data);
11+
}
12+
13+
dequeue() {
14+
if (!this.queue.peek()) {
15+
return null;
16+
}
17+
18+
// pop all the element to the temp stack
19+
while (this.queue.peek()) this.temp.push(this.queue.pop());
20+
const el = this.temp.pop();
21+
22+
// push all the temp items to the queue again
23+
while (this.temp.peek()) this.queue.push(this.temp.pop());
24+
return el;
25+
}
26+
}
27+
28+
module.exports = Queue;

0 commit comments

Comments
 (0)