Skip to content

Commit 9353535

Browse files
Create 0232-implement-queue-using-stacks.js
1 parent e170ea3 commit 9353535

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// https://leetcode.com/problems/implement-queue-using-stacks/
2+
3+
var MyQueue = function() {
4+
this.stack1 = [];
5+
this.stack2 = [];
6+
};
7+
8+
/**
9+
* @param {number} x
10+
* @return {void}
11+
*/
12+
MyQueue.prototype.push = function(x) {
13+
this.stack1.push(x);
14+
};
15+
16+
/**
17+
* @return {number}
18+
*/
19+
MyQueue.prototype.pop = function() {
20+
this.swappingStacks();
21+
22+
if(!this.stack2.length){
23+
return null;
24+
}
25+
return this.stack2.pop();
26+
};
27+
28+
/**
29+
* @return {number}
30+
*/
31+
MyQueue.prototype.peek = function() {
32+
this.swappingStacks();
33+
return this.stack2.length == 0 ? null : this.stack2[this.stack2.length-1]
34+
};
35+
36+
/**
37+
* @return {boolean}
38+
*/
39+
MyQueue.prototype.empty = function() {
40+
return this.stack1.length === 0 && this.stack2.length === 0;
41+
};
42+
43+
MyQueue.prototype.swappingStacks = function() {
44+
if (this.stack1.length) {
45+
this.stack2 = [...this.stack1.reverse(), ...this.stack2];
46+
this.stack1 = [];
47+
}
48+
}
49+
50+
/**
51+
* Your MyQueue object will be instantiated and called as such:
52+
* var obj = new MyQueue()
53+
* obj.push(x)
54+
* var param_2 = obj.pop()
55+
* var param_3 = obj.peek()
56+
* var param_4 = obj.empty()
57+
*/

0 commit comments

Comments
 (0)