@@ -281,48 +281,54 @@ class MyQueue {
281
281
282
282
Python:
283
283
``` python
284
- # 使用两个栈实现先进先出的队列
285
284
class MyQueue :
285
+
286
286
def __init__ (self ):
287
287
"""
288
- Initialize your data structure here.
288
+ in主要负责push,out主要负责pop
289
289
"""
290
- self .stack1 = list ()
291
- self .stack2 = list ()
290
+ self .stack_in = []
291
+ self .stack_out = []
292
+
292
293
293
294
def push (self , x : int ) -> None :
294
295
"""
295
- Push element x to the back of queue.
296
+ 有新元素进来,就往in里面push
296
297
"""
297
- # self.stack1用于接受元素
298
- self .stack1.append(x)
298
+ self .stack_in.append(x)
299
+
299
300
300
301
def pop (self ) -> int :
301
302
"""
302
- Removes the element from in front of queue and returns that element.
303
+ 1. 检查如果out里面元素,则直接pop
304
+ 2. 如果out没有元素,就把in里面的元素(除了第一个)依次pop后装进out里面
305
+ 3. 直接把in剩下的元素pop出来,就是queue头部的
303
306
"""
304
- # self.stack2用于弹出元素,如果self.stack2为[],则将self.stack1中元素全部弹出给self.stack2
305
- if self .stack2 == []:
306
- while self .stack1:
307
- tmp = self .stack1.pop()
308
- self .stack2.append(tmp)
309
- return self .stack2.pop()
307
+ if self .stack_out:
308
+ return self .stack_out.pop()
309
+ else :
310
+ for i in range (1 , len (self .stack_in)):
311
+ self .stack_out.append(self .stack_in.pop())
312
+ return self .stack_in.pop()
313
+
310
314
311
315
def peek (self ) -> int :
312
316
"""
313
- Get the front element.
317
+ 1. 查out有没有元素,有就把最上面的返回
318
+ 2. 如果out没有元素,就把in最下面的返回
314
319
"""
315
- if self .stack2 == [] :
316
- while self .stack1:
317
- tmp = self .stack1.pop()
318
- self .stack2.append(tmp)
319
- return self .stack2[ - 1 ]
320
+ if self .stack_out :
321
+ return self .stack_out[ - 1 ]
322
+ else :
323
+ return self .stack_in[ 0 ]
324
+
320
325
321
326
def empty (self ) -> bool :
322
327
"""
323
- Returns whether the queue is empty.
328
+ 只要in或者out有元素,说明队列不为空
324
329
"""
325
- return self .stack1 == [] and self .stack2 == []
330
+ return not (self .stack_in or self .stack_out)
331
+
326
332
```
327
333
328
334
0 commit comments