码迷,mamicode.com
首页 > 其他好文 > 详细

009.栈实现队列

时间:2018-12-04 19:02:35      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:iat   while   return   and   rom   ali   push   The   anti   

class MyQueue(object):

    def __init__(self, ):
        """
        Initialize your data structure here.
        """
        self.instack = []
        self.outstack = []

    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        self.instack.append(x)

    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        if not self.outstack:
            if not self.instack:
                return
            else:
                while self.instack:
                    node = self.instack.pop()
                    self.outstack.append(node)
        return self.outstack.pop()

    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        if not self.outstack:
            if not self.instack:
                return
            else:
                while self.instack:
                    node = self.instack.pop()
                    self.outstack.append(node)
        return self.outstack[-1]

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        if len(self.instack) == 0 and len(self.outstack) == 0:
            return True
        else:
            return False

# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

  

009.栈实现队列

标签:iat   while   return   and   rom   ali   push   The   anti   

原文地址:https://www.cnblogs.com/wanyp/p/10065602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!