Leetcode 232. Implement Queue using Stacks

这道题的意思是用堆栈来实现队列,pop和peak是去除和获取最前面的元素。下面就是我用python通过的代码

class MyQueue(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack = []
        self.top = -1

    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        self.stack.append(x)
        self.top = self.top+1

    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        if self.empty():
            raise Exception("stack is empty")
        else:
            self.top = self.top-1
            return self.stack.pop(0)

    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        return self.stack[0]

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        return self.top == -1

猜你喜欢

转载自blog.csdn.net/cainiaohudi/article/details/79861277