题解 | #用两个栈实现队列python实现#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
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 len(self.stack2) > 0 : #当弹出栈不为空时,弹出最右侧值 return self.stack2.pop() elif len(self.stack1) == 0: # 当弹出栈和压入栈都为空时,返回None return None else: # 当弹出栈为空,压入栈不为空时,将压入栈中的值反向后复制到弹出栈中,并删除原来的值 self.stack2 = self.stack1.copy() self.stack2.reverse() self.stack1 = [] return self.stack2.pop()