'''
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
'''
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
self.stack1.append(node)
def pop(self):
if len(self.stack1) == 0 and len(self.stack2) == 0:
return
elif len(self.stack2) == 0:
while len(self.stack1) > 0:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
if __name__ == '__main__':
solution = Solution()
solution.push(1)
solution.push(2)
solution.push(3)
print(solution.pop())
solution.push(4)
print(solution.pop())
print(solution.pop())
print(solution.pop())
剑指offer python版 9.1用两个栈实现队列
最新推荐文章于 2021-09-09 14:55:34 发布