Update 修正 0225.用队列实现栈 python代码

This commit is contained in:
Siqi Cao
2023-08-27 14:13:18 -04:00
committed by GitHub
parent e48b94f97d
commit ca197783d2

View File

@ -454,13 +454,34 @@ class MyStack:
def top(self) -> int: def top(self) -> int:
""" """
写法一:
1. 首先确认不空 1. 首先确认不空
2. 我们仅有in会存放数据所以返回第一个即可 2. 我们仅有in会存放数据所以返回第一个即可(这里实际上用到了栈)
写法二:
1. 首先确认不空
2. 因为队列的特殊性FIFO所以我们只有在pop()的时候才会使用queue_out
3. 先把queue_in中的所有元素除了最后一个依次出列放进queue_out
4. 交换in和out此时out里只有一个元素
5. 把out中的pop出来即是原队列的最后一个并使用temp变量暂存
6. 把temp追加到queue_in的末尾
""" """
# 写法一:
# if self.empty():
# return None
# return self.queue_in[-1] # 这里实际上用到了栈因为直接获取了queue_in的末尾元素
# 写法二:
if self.empty(): if self.empty():
return None return None
return self.queue_in[-1] for i in range(len(self.queue_in) - 1):
self.queue_out.append(self.queue_in.popleft())
self.queue_in, self.queue_out = self.queue_out, self.queue_in
temp = self.queue_out.popleft()
self.queue_in.append(temp)
return temp
def empty(self) -> bool: def empty(self) -> bool:
@ -488,9 +509,19 @@ class MyStack:
return self.que.popleft() return self.que.popleft()
def top(self) -> int: def top(self) -> int:
# 写法一:
# if self.empty():
# return None
# return self.que[-1]
# 写法二:
if self.empty(): if self.empty():
return None return None
return self.que[-1] for i in range(len(self.que)-1):
self.que.append(self.que.popleft())
temp = self.que.popleft()
self.que.append(temp)
return temp
def empty(self) -> bool: def empty(self) -> bool:
return not self.que return not self.que