题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
题目地址
思路
入栈时把数据压入stack1,
出栈时若stack2不为空,直接弹出,
若stack2为空,则将stack1的全部元素压入stack2,在弹出stack2.
Python
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
# write code here
self.stack1.append(node) def pop(self):
# return xx
if self.stack2:
return self.stack2.pop()
else:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop() if __name__ == '__main__':
result = Solution()
result.push(1)
result.push(2)
result.pop()
result.push(4)
result.pop()
result.pop()