首页 > 其他 > 详细

232. 用栈实现队列

时间:2020-05-16 14:08:25      阅读:48      评论:0      收藏:0      [点我收藏+]

技术分享图片
技术分享图片
技术分享图片

思路:

用两个栈: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

232. 用栈实现队列

原文:https://www.cnblogs.com/panweiwei/p/12900185.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!