009.栈实现队列

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()

  

猜你喜欢

转载自www.cnblogs.com/wanyp/p/10065602.html