mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
更新 0232.用栈实现队列.md python代码
python代码简化,符合PEP8标准,可读性加强,效率提升
This commit is contained in:
@ -281,48 +281,54 @@ class MyQueue {
|
|||||||
|
|
||||||
Python:
|
Python:
|
||||||
```python
|
```python
|
||||||
# 使用两个栈实现先进先出的队列
|
|
||||||
class MyQueue:
|
class MyQueue:
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
"""
|
"""
|
||||||
Initialize your data structure here.
|
in主要负责push,out主要负责pop
|
||||||
"""
|
"""
|
||||||
self.stack1 = list()
|
self.stack_in = []
|
||||||
self.stack2 = list()
|
self.stack_out = []
|
||||||
|
|
||||||
|
|
||||||
def push(self, x: int) -> None:
|
def push(self, x: int) -> None:
|
||||||
"""
|
"""
|
||||||
Push element x to the back of queue.
|
有新元素进来,就往in里面push
|
||||||
"""
|
"""
|
||||||
# self.stack1用于接受元素
|
self.stack_in.append(x)
|
||||||
self.stack1.append(x)
|
|
||||||
|
|
||||||
def pop(self) -> int:
|
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.stack_out:
|
||||||
if self.stack2 == []:
|
return self.stack_out.pop()
|
||||||
while self.stack1:
|
else:
|
||||||
tmp = self.stack1.pop()
|
for i in range(1, len(self.stack_in)):
|
||||||
self.stack2.append(tmp)
|
self.stack_out.append(self.stack_in.pop())
|
||||||
return self.stack2.pop()
|
return self.stack_in.pop()
|
||||||
|
|
||||||
|
|
||||||
def peek(self) -> int:
|
def peek(self) -> int:
|
||||||
"""
|
"""
|
||||||
Get the front element.
|
1. 查out有没有元素,有就把最上面的返回
|
||||||
|
2. 如果out没有元素,就把in最下面的返回
|
||||||
"""
|
"""
|
||||||
if self.stack2 == []:
|
if self.stack_out:
|
||||||
while self.stack1:
|
return self.stack_out[-1]
|
||||||
tmp = self.stack1.pop()
|
else:
|
||||||
self.stack2.append(tmp)
|
return self.stack_in[0]
|
||||||
return self.stack2[-1]
|
|
||||||
|
|
||||||
def empty(self) -> bool:
|
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