'''
用两个队列来实现一个栈,完成栈的Push和Pop操作。 栈中的元素为int类型。
'''
class Solution:
def __init__(self):
self.queue1 = []
self.queue2 = []
def push(self, x):
if self.queue2 == []:
self.queue1.append(x)
else:
self.queue2.append(x)
def pop(self):
if self.queue1 == [] and self.queue2 == []:
return
if self.queue1 != []:
length = len(self.queue1)
for i in range(length - 1):
self.queue2.append(self.queue1.pop(0))
return self.queue1.pop()
else:
length = len(self.queue2)
for i in range(length - 1):
self.queue1.append(self.queue2.pop(0))
return self.queue2.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())
11-21
1513
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)