zoukankan      html  css  js  c++  java
  • 232. 用栈实现队列





    思路:

    用两个栈:stackIn[] 和 stackOut[]分别模拟入队和出队;
    注意:
    出队时,只有当stackOut为空时才能将stackIn的元素入栈stackOut,且必须将stackIn的元素一次性全部转移到stackOut中,再出队。
    进队时:只有当待入队元素全部进入stackIn后才能转移到stackOut,从而出队,且入队前若stackIn不为空则需等待。

    class MyQueue(object):
        # 初始化
        def __init__(self):
            """
            Initialize your data structure here.
            """
            # 入栈,模拟进队
            self.stackIn = []
            # 出栈,模拟出队
            self.stackOut = []
    
        # 进队,本题似乎不用考虑stackIn不为空的情况,进队时默认stackIn为空
        def push(self, x):
            """
            Push element x to the back of queue.
            :type x: int
            :rtype: None
            """
            self.stackIn.append(x)
    
        # 出队
        def pop(self):
            """
            Removes the element from in front of queue and returns that element.
            :rtype: int
            """
            if not self.stackOut:
                while self.stackIn:
                    self.stackOut.append(self.stackIn.pop())
                return self.stackOut.pop()
            else:
                return self.stackOut.pop()
    
        # 取队首元素
        def peek(self):
            """
            Get the front element.
            :rtype: int
            """
            if not self.stackOut:
                while self.stackIn:
                    self.stackOut.append(self.stackIn.pop())
                return self.stackOut[-1]
            else:
                return self.stackOut[-1]
    
        # 队列判空:只有当stackIn和stackOut均为空时,队列为空。
        def empty(self):
            """
            Returns whether the queue is empty.
            :rtype: bool
            """
            return not self.stackIn and not self.stackOut
    

  • 相关阅读:
    js实现将字符串里包含手机号的中间四位替换为****
    草稿for套for
    js实现将时间戳转换成2017-05-06 09:03:02
    时间日期校验接口
    JS延迟导航nav
    nav导航
    鼠标滚动请求加载
    常用开源Jabber(XMPP) IM服务器介绍(转)
    01.base-v1.js
    Haproxy安装及配置(转)
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12900185.html
Copyright © 2011-2022 走看看