前往此题

解题思路

两个辅助栈cur,tmp,一个负责入队,一个负责出队。因为栈是先进后出,队是先进先出的规则,所以我们在用栈来模拟队的pop函数的时候需要把栈倒叙后再执行pop

代码

class MyQueue:

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

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.cur.append(x)


    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if not self.tmp:
            while self.cur:
                self.tmp.append(self.cur.pop())
        return self.tmp.pop()


    def peek(self) -> int:
        """
        Get the front element.
        """
        if not self.tmp:
            while self.cur:
                self.tmp.append(self.cur.pop())
        return self.tmp[-1]


    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return not self.cur and not self.tmp