用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
创建两个栈S1和S2,入队时,将元素压入S1,出队时,如果栈S2中的元素个数为0,则将S1中的元素一个个压入S2,并弹出最后压入的那个元素,如果栈S2中的元素个数不为0,则直接弹出S2中的顶元素。
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
self.stack1.append(node)
def pop(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()