wangyp

博客园 首页 联系 订阅 管理
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()

  

posted on 2018-12-04 17:43  wangyp  阅读(135)  评论(0编辑  收藏  举报