先简单回顾一下,今天预计分析的题目:
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
# 分别宣告两个 stack,命名为 stack1 与 stack2
# stack1 放存进来的值
# stack2 是把 stack1 的值逐一放入stack2,变成 Queue 的形式(最早放的会在最上面)
self.stack1 = []
self.stack2 = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
# 呼叫 push function 时,会把变数 x 放进 stack1 中
self.stack1.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
# 呼叫 pop function 时,要拿出最早放入的值,所以先看看 stack2 有没有值 ( stack2 是已经变成 Queue 排列的顺序)
# stack2 若是空的,就把 stack1 的值逐一放入 stack2
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
# 回传 stack2 最上面的值
return self.stack2.pop()
def peek(self) -> int:
"""
Get the front element.
"""
# 跟上面 pop function 一样,判断stack2 是不是空的,若是空的,就把 stack1 的值逐一放入 stack2
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
# 由於是 peek,只会看最前面是什麽,不会把值拿出来,所以拿出来後还要储存回去
top = self.stack2.pop()
self.stack2.append(top)
return top
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
# 检查 stack1 跟 stack2 是不是空的
if self.stack1 or self.stack2:
return False
else:
return True
def peek(self) -> int:
# 判断 stack2 是否为空,若不为空,则回传 stack中 最後一个值 (也就是最上面的)
# 若 stack2 为空,则回传 stack1 最底下的值 (最先放的值)
if self.stack2:
return self.stack2[-1]
else:
return self.stack1[0]
def empty(self) -> bool:
# 看 stack 的长度,若为 0 则代表 stack 为空
if len(self.stack1)==0 and len(self.stack2)==0:
return True
return False
class MyQueue:
def __init__(self):
self.stack3 = []
def push(self, x: int) -> None:
self.stack3.append(x)
def pop(self) -> int:
return self.stack3.pop(0)
def peek(self) -> int:
return self.stack3[0]
def empty(self) -> bool:
if self.stack3:
return False
return True
<<: < 关於 React: 开始打地基| function、class function >
大家好,我想介绍一下自己为什麽会认识spring boot,因为写後端API的时候会用到的框架 然後...
CredentialsFileView 今天就来认识 CredentialsFileView 这个工...
呈前一天的问题!昨日的答案是因为我们有在 yml 档设定 production 的环境要使用 pgs...
Pointer to Pointer 顾名思义就是指标的指标~ 它可能是一个变数的地址的地址~ 我们...
第12 届iT邦帮忙铁人赛系列文章 (Day28) SignalR是实现即时通讯的框架,如下图,在S...