题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
栈是保证元素后进先出,队列保证元素先进先出,它们都只有到来先后顺序
python中用list来提供栈和队列的功能,对于栈而言,要实现后进先出,出的方式只有list.pop(),pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值,所以压入元素存入list的尾部,list.append(x),压出用pop()。对于队列,先进先出,先进的存在list的头部[0],存入在队尾o(1),压出在队头,不好用pop(0)来压出,因为压出需要将其后元素统统移位置o(n),所以使用顺序表实现队列有一定困难。
题目思路:需要用两个栈来实现一个队列,一个栈A是先进后出,将栈A中出的元素存放在栈B中,负负得正,实现队列的先进先出功能。存入时,存在栈A,存在尾部。弹出时,如果栈A不空,先全部弹出到栈B,再分别从栈B弹出。
def push(self, node): # write code here self.stackA.append(node)
class Solution:
def __init__(self):
self.stackA=[]
self.stackB=[]
def push(self, node):
# write code here
self.stackA.append(node)
def pop(self):
# return xx
if self.stackB:
return self.stackB.pop()
elif not self.stackA:
return None
else:
while self.stackA:
self.stackB.append(self.stackA.pop())
return self.stackB.pop()