剑指Offer 5. 用两个栈实现队列 (栈)

Posted on 2018-10-11 22:29  _hqc  阅读(139)  评论(0编辑  收藏  举报

题目描述

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

题目地址

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

思路

入栈时把数据压入stack1,

出栈时若stack2不为空,直接弹出,

若stack2为空,则将stack1的全部元素压入stack2,在弹出stack2.

Python

# -*- coding:utf-8 -*-
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 self.stack2:
            return self.stack2.pop()
        else:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
            return self.stack2.pop()

if __name__ == '__main__':
    result = Solution()
    result.push(1)
    result.push(2)
    result.pop()
    result.push(4)
    result.pop()
    result.pop()