题解 | #用两个栈实现队列#
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
# write code here
# n = len(self.stack1)
self.stack1.append(node)
pass
def pop(self):
# return xx
# 第一个栈中内容弹出,放入第二个栈中
while self.stack1:
self.stack2.append(self.stack1.pop())
# 第二个栈顶即最先进来的元素, 及队首
rst = self.stack2.pop()
# 第二个栈元素放回第一个栈中
while self.stack2:
self.stack1.append(self.stack2.pop())
return rst
pass
进栈方法使用 列表实现; 出栈方法要构造队列特性:先进先出,而且要保证 list的pop方法特性。
SHEIN希音公司福利 325人发布
