From a69006f901230b1ba73e73ce8b86918b404480e4 Mon Sep 17 00:00:00 2001 From: Eyjan_Huang <81480748+Eyjan-Huang@users.noreply.github.com> Date: Fri, 20 Aug 2021 00:06:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200232.=E7=94=A8=E6=A0=88?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E9=98=9F=E5=88=97.md=20python=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit python代码简化,符合PEP8标准,可读性加强,效率提升 --- problems/0232.用栈实现队列.md | 50 ++++++++++++++++------------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 0df82d35..46d884d3 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -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) + ```