File tree Expand file tree Collapse file tree 1 file changed +53
-3
lines changed Expand file tree Collapse file tree 1 file changed +53
-3
lines changed Original file line number Diff line number Diff line change @@ -16,7 +16,7 @@ Example:
16
16
MyQueue queue = new MyQueue();
17
17
18
18
queue.push(1);
19
- queue.push(2);
19
+ queue.push(2);
20
20
queue.peek(); // returns 1
21
21
queue.pop(); // returns 1
22
22
queue.empty(); // returns false
@@ -64,9 +64,11 @@ push之前是这样的:
64
64
65
65
## 代码
66
66
67
- ``` js
67
+ * 语言支持:JS, Python
68
68
69
+ Javascript Code:
69
70
71
+ ``` js
70
72
/*
71
73
* @lc app=leetcode id=232 lang=javascript
72
74
*
@@ -132,7 +134,55 @@ MyQueue.prototype.empty = function() {
132
134
*/
133
135
```
134
136
137
+ Python Code:
138
+
139
+ ``` python
140
+ class MyQueue :
141
+
142
+ def __init__ (self ):
143
+ """
144
+ Initialize your data structure here.
145
+ """
146
+ self .stack = []
147
+ self .help_stack = []
148
+
149
+ def push (self , x : int ) -> None :
150
+ """
151
+ Push element x to the back of queue.
152
+ """
153
+ while self .stack:
154
+ self .help_stack.append(self .stack.pop())
155
+ self .help_stack.append(x)
156
+ while self .help_stack:
157
+ self .stack.append(self .help_stack.pop())
158
+
159
+ def pop (self ) -> int :
160
+ """
161
+ Removes the element from in front of queue and returns that element.
162
+ """
163
+ return self .stack.pop()
164
+
165
+ def peek (self ) -> int :
166
+ """
167
+ Get the front element.
168
+ """
169
+ return self .stack[- 1 ]
170
+
171
+ def empty (self ) -> bool :
172
+ """
173
+ Returns whether the queue is empty.
174
+ """
175
+ return not bool (self .stack)
176
+
177
+
178
+ # Your MyQueue object will be instantiated and called as such:
179
+ # obj = MyQueue()
180
+ # obj.push(x)
181
+ # param_2 = obj.pop()
182
+ # param_3 = obj.peek()
183
+ # param_4 = obj.empty()
184
+ ```
185
+
135
186
## 扩展
136
187
- 类似的题目有用队列实现栈,思路是完全一样的,大家有兴趣可以试一下。
137
188
- 栈混洗也是借助另外一个栈来完成的,从这点来看,两者有相似之处。
138
-
You can’t perform that action at this time.
0 commit comments