Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a69006f

Browse files
更新 0232.用栈实现队列.md python代码
python代码简化,符合PEP8标准,可读性加强,效率提升
1 parent 1a82f98 commit a69006f

File tree

1 file changed

+28
-22
lines changed

1 file changed

+28
-22
lines changed

‎problems/0232.用栈实现队列.md‎

Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -281,48 +281,54 @@ class MyQueue {
281281

282282
Python:
283283
```python
284-
# 使用两个栈实现先进先出的队列
285284
class MyQueue:
285+
286286
def __init__(self):
287287
"""
288-
Initialize your data structure here.
288+
in主要负责push,out主要负责pop
289289
"""
290-
self.stack1 = list()
291-
self.stack2 = list()
290+
self.stack_in = []
291+
self.stack_out = []
292+
292293

293294
def push(self, x: int) -> None:
294295
"""
295-
Push element x to the back of queue.
296+
有新元素进来,就往in里面push
296297
"""
297-
#self.stack1用于接受元素
298-
self.stack1.append(x)
298+
self.stack_in.append(x)
299+
299300

300301
def pop(self) -> int:
301302
"""
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头部的
303306
"""
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+
310314

311315
def peek(self) -> int:
312316
"""
313-
Get the front element.
317+
1. 查out有没有元素,有就把最上面的返回
318+
2. 如果out没有元素,就把in最下面的返回
314319
"""
315-
if self.stack2 == []:
316-
while self.stack1:
317-
tmp =self.stack1.pop()
318-
self.stack2.append(tmp)
319-
returnself.stack2[-1]
320+
if self.stack_out:
321+
return self.stack_out[-1]
322+
else:
323+
returnself.stack_in[0]
324+
320325

321326
def empty(self) -> bool:
322327
"""
323-
Returns whether the queue is empty.
328+
只要in或者out有元素,说明队列不为空
324329
"""
325-
return self.stack1 == [] and self.stack2 == []
330+
return not (self.stack_in or self.stack_out)
331+
326332
```
327333

328334

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /