一、理论基础
栈:先进后出
队列:先进先出
二、用栈实现队列
pop.()函数 : 删除最后一个元素
class MyQueue:
def __init__(self):
self.stack_in = [] # 进栈
self.stack_out = [] # 出栈
def push(self, x: int) -> None:
self.stack_in.append(x) # 往进栈里加入新元素 进队列
def pop(self) -> int:
if len(self.stack_out)==0: # 如果out为空,将in中的所有元素追加到out中
while len(self.stack_in)!=0: # 只有in中元素不为空
self.stack_out.append(self.stack_in.pop()) # 将in中的所有元素追加到out中
return self.stack_out.pop() # 删除并返回队列开头元素
def peek(self) -> int:
if len(self.stack_out)==0: # 如果out为空,将in中的所有元素追加到out中
while len(self.stack_in)!=0: # 只有in中元素不为空
self.stack_out.append(self.stack_in.pop()) # 将in中的所有元素追加到out中
return self.stack_out[-1] # 只返回不删除
def empty(self) -> bool:
if len(self.stack_in) == 0 and len(self.stack_out) == 0:
return True
return False
三、用队列实现栈
class MyStack:
def __init__(self):
self.stack = deque() # 创造两个双端队列
self.help = deque()
def push(self, x: int) -> None: # 增加元素
self.stack.append(x)
def pop(self) -> int: # 删除并获取栈顶元素
while len(self.stack)>1: # 只要stack中有1个以上的元素
self.help.append(self.stack.popleft()) # 把stack中左侧的元素删除并添加到help中,循环
tem = self.stack.popleft() # 不加到help 删除stack中的元素(只有一个)
self.stack,self.help = self.help,self.stack #交换位置,使得help为空,stack被删一个元素
return tem
def top(self) -> int: # 只获取,不删除
while len(self.stack)>1:
self.help.append(self.stack.popleft())
tem = self.stack.popleft()
self.help.append(tem) # 加到help 没有删除 。help中有tem。
self.stack,self.help = self.help,self.stack
return tem
def empty(self) -> bool:
if len(self.stack)==0 and len(self.help)==0:
return True
return False