LeetCode 225 [Implement Stack by Two Queues]

原题

利用两个队列来实现一个栈的功能

样例

push(1)
pop()
push(2)
isEmpty() // return false
top() // return 2
pop()
isEmpty() // return true

解题思路

  • 使用两个queue
q1 = []       q2 = []
push 1
q1 = [1]      q2 = []
q1 = []       q2 = [1] 
push 2
q1 = [2]      q2 = [1]
q1 = [2, 1]   q2 = []
q1 = []       q2 = [2, 1]
push 3
q1 = [3]       q2 = [2, 1]   
q1 = [3, 2, 1] q2 = []
q1 = []        q2 = [3, 2, 1]

完整代码

import Queue

class Stack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.q1 = Queue.Queue()
        self.q2 = Queue.Queue()

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.q1.put(x)
        while self.q2.qsize() != 0:
            self.q1.put(self.q2.get())
        while self.q1.qsize() != 0:
            self.q2.put(self.q1.get())
        

    def pop(self):
        """
        :rtype: nothing
        """
        self.q2.get()
        

    def top(self):
        """
        :rtype: int
        """
        return self.q2.queue[0]
        

    def empty(self):
        """
        :rtype: bool
        """
        return self.q2.qsize() == 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 星期天小哼和小哈约在一起玩桌游,他们正在玩一个非常古怪的扑克游戏——“小猫钓鱼”。游戏的规则是这样的:将一副扑克牌...
    青葱烈马阅读 5,458评论 0 0
  • 一、前言 本篇博文介绍的是iOS中常用的几个多线程技术: NSThread GCD NSOperation 由于a...
    和珏猫阅读 3,682评论 0 1
  • 1、字符串反转 写一个方法,要求:输入一个字符串ABCDEFG,要求倒序输出GFEDCBA: // 方法1 - ...
    DevWang阅读 4,705评论 0 49
  • 一、前言 上一篇文章iOS多线程浅汇-原理篇中整理了一些有关多线程的基本概念。本篇博文介绍的是iOS中常用的几个多...
    nuclear阅读 6,261评论 6 18

友情链接更多精彩内容