Skip to content

Commit 5e45452

Browse files
committed
232.用栈实现队列 (二刷)
1 parent de8b04a commit 5e45452

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

vs-lt/232.用栈实现队列.js

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
* @lc app=leetcode.cn id=232 lang=javascript
3+
*
4+
* [232] 用栈实现队列
5+
*/
6+
7+
// @lc code=start
8+
9+
var MyQueue = function() {
10+
this.stackIn = [];
11+
this.stackOut = [];
12+
};
13+
14+
/**
15+
* @param {number} x
16+
* @return {void}
17+
*/
18+
MyQueue.prototype.push = function(x) {
19+
this.stackIn.push(x);
20+
};
21+
22+
/**
23+
* @return {number}
24+
*/
25+
MyQueue.prototype.pop = function() {
26+
// in: [1, 2, 3, 4]
27+
// out: []
28+
// =>
29+
// in: []
30+
// out: [4, 3, 2, 1]
31+
32+
// 如果输出栈为空, 将输入栈的数据全部导入输出栈
33+
if (this.stackOut.length === 0) {
34+
let size = this.stackIn.length;
35+
while (size--) {
36+
this.stackOut.push(this.stackIn.pop());
37+
}
38+
}
39+
return this.stackOut.pop();
40+
};
41+
42+
/**
43+
* @return {number}
44+
*/
45+
MyQueue.prototype.peek = function() {
46+
// 复用已有方法
47+
const result = this.pop();
48+
this.stackOut.push(result);
49+
return result;
50+
};
51+
52+
/**
53+
* @return {boolean}
54+
*/
55+
MyQueue.prototype.empty = function() {
56+
return this.stackIn.length === 0 && this.stackOut.length === 0;
57+
};
58+
59+
/**
60+
* Your MyQueue object will be instantiated and called as such:
61+
* var obj = new MyQueue()
62+
* obj.push(x)
63+
* var param_2 = obj.pop()
64+
* var param_3 = obj.peek()
65+
* var param_4 = obj.empty()
66+
*/
67+
// @lc code=end
68+

0 commit comments

Comments
 (0)