mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
更新 0232.用栈实现队列.md python代码
python代码简化,符合PEP8标准,可读性加强,效率提升
This commit is contained in:
@ -281,48 +281,54 @@ class MyQueue {
|
||||
|
||||
Python:
|
||||
```python
|
||||
# 使用两个栈实现先进先出的队列
|
||||
class MyQueue:
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
Initialize your data structure here.
|
||||
in主要负责push,out主要负责pop
|
||||
"""
|
||||
self.stack1 = list()
|
||||
self.stack2 = list()
|
||||
self.stack_in = []
|
||||
self.stack_out = []
|
||||
|
||||
|
||||
def push(self, x: int) -> None:
|
||||
"""
|
||||
Push element x to the back of queue.
|
||||
有新元素进来,就往in里面push
|
||||
"""
|
||||
# self.stack1用于接受元素
|
||||
self.stack1.append(x)
|
||||
self.stack_in.append(x)
|
||||
|
||||
|
||||
def pop(self) -> int:
|
||||
"""
|
||||
Removes the element from in front of queue and returns that element.
|
||||
1. 检查如果out里面元素,则直接pop
|
||||
2. 如果out没有元素,就把in里面的元素(除了第一个)依次pop后装进out里面
|
||||
3. 直接把in剩下的元素pop出来,就是queue头部的
|
||||
"""
|
||||
# self.stack2用于弹出元素,如果self.stack2为[],则将self.stack1中元素全部弹出给self.stack2
|
||||
if self.stack2 == []:
|
||||
while self.stack1:
|
||||
tmp = self.stack1.pop()
|
||||
self.stack2.append(tmp)
|
||||
return self.stack2.pop()
|
||||
if self.stack_out:
|
||||
return self.stack_out.pop()
|
||||
else:
|
||||
for i in range(1, len(self.stack_in)):
|
||||
self.stack_out.append(self.stack_in.pop())
|
||||
return self.stack_in.pop()
|
||||
|
||||
|
||||
def peek(self) -> int:
|
||||
"""
|
||||
Get the front element.
|
||||
1. 查out有没有元素,有就把最上面的返回
|
||||
2. 如果out没有元素,就把in最下面的返回
|
||||
"""
|
||||
if self.stack2 == []:
|
||||
while self.stack1:
|
||||
tmp = self.stack1.pop()
|
||||
self.stack2.append(tmp)
|
||||
return self.stack2[-1]
|
||||
if self.stack_out:
|
||||
return self.stack_out[-1]
|
||||
else:
|
||||
return self.stack_in[0]
|
||||
|
||||
|
||||
def empty(self) -> bool:
|
||||
"""
|
||||
Returns whether the queue is empty.
|
||||
只要in或者out有元素,说明队列不为空
|
||||
"""
|
||||
return self.stack1 == [] and self.stack2 == []
|
||||
return not (self.stack_in or self.stack_out)
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user