class MyStack:
def __init__(self):
#A是存放栈前n-1个的队列,B是存放栈最后弹出的元素
self.que_in ,self.que_out = deque(),deque()
def push(self, x: int) -> None:
self.que_in.append(x)
def pop(self) -> int:
if not self.que_in:
return None
for i in range(len(self.que_in) -1):
self.que_out.append(self.que_in.popleft())
self.que_out,self.que_in = self.que_in,self.que_out
T = self.que_out.popleft()
return T
def top(self) -> int:
if not self.que_in:
return None
for i in range(len(self.que_in) -1):
self.que_out.append(self.que_in.popleft())
self.que_out,self.que_in = self.que_in,self.que_out
swap = self.que_out.popleft()
self.que_in.append(swap)
return swap
def empty(self) -> bool:
if len(self.que_in) ==0:
return True
else:
return False
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
总结:1.构建一个双端队列用 a = deque() 2.选择将队列从左边弹出 a.popleft() 3.注意当找寻栈的第一个元素时,将第二个队列中的元素(有且只有一个)弹出加入到第一个队列中(第一个队列中存有栈里元素数量-1个)