用两个栈实现队列

用两个栈实现队列_牛客网

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:
栈A用来作入队列
栈B用来出队列,当栈B为空时,栈A全部出栈到栈B,栈B再出栈(即出队列)

AC代码:

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==[]:
        while self.stack1:
            self.stack2.append(self.stack1.pop())
    return self.stack2.pop()
全部评论

相关推荐

05-22 12:44
已编辑
门头沟学院 golang
点赞 评论 收藏
分享
评论
32
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务