File tree 1 file changed +71
-0
lines changed
1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=225 lang=javascript
3
+ *
4
+ * [225] 用队列实现栈
5
+ */
6
+
7
+ // @lc code=start
8
+
9
+ var MyStack = function ( ) {
10
+ this . queue = [ ] ;
11
+ this . backup = [ ] ;
12
+ } ;
13
+
14
+ /**
15
+ * @param {number } x
16
+ * @return {void }
17
+ */
18
+ MyStack . prototype . push = function ( x ) {
19
+ this . queue . push ( x ) ;
20
+ } ;
21
+
22
+ /**
23
+ * @return {number }
24
+ */
25
+ MyStack . prototype . pop = function ( ) {
26
+ // 思路: 对 queue 执行出队操作, 当 queue 中只剩一个元素时, 队头元素就是 栈顶元素.
27
+ // queue: [1, 2, 3, 4]
28
+ // backup: []
29
+ // =>
30
+ // queue: [4]
31
+ // backup: [1, 2, 3]
32
+ // =>
33
+ // queue: [4, 1, 2, 3]
34
+ // backup: []
35
+
36
+ while ( this . queue . length > 1 ) {
37
+ this . backup . push ( this . queue . shift ( ) ) ;
38
+ }
39
+ while ( this . backup . length > 0 ) {
40
+ this . queue . push ( this . backup . shift ( ) ) ;
41
+ }
42
+
43
+ return this . queue . shift ( ) ;
44
+ } ;
45
+
46
+ /**
47
+ * @return {number }
48
+ */
49
+ MyStack . prototype . top = function ( ) {
50
+ const result = this . pop ( ) ;
51
+ this . push ( result ) ;
52
+ return result ;
53
+ } ;
54
+
55
+ /**
56
+ * @return {boolean }
57
+ */
58
+ MyStack . prototype . empty = function ( ) {
59
+ return this . queue . length === 0 ;
60
+ } ;
61
+
62
+ /**
63
+ * Your MyStack object will be instantiated and called as such:
64
+ * var obj = new MyStack()
65
+ * obj.push(x)
66
+ * var param_2 = obj.pop()
67
+ * var param_3 = obj.top()
68
+ * var param_4 = obj.empty()
69
+ */
70
+ // @lc code=end
71
+
You can’t perform that action at this time.
0 commit comments