相关题目
225. 用队列实现栈:弹出元素时,将对首的元素出列加到队尾,直到只剩下初始队列时队尾一个元素为止,然后弹出这个元素,即可实现LIFO
232. 用栈实现队列:用两个栈实现队列的功能,出栈时,将栈1的元素全部弹出压到栈2中,然后弹出栈2栈顶的元素,即可实现FIFO

#  225. 用队列实现栈
class MyStack:

    def __init__(self):
        self.queue = []


    def push(self, x: int) -> None:
        self.queue.append(x)


    def pop(self) -> int:
        n = len(self.queue)
        while n > 1:
            self.queue.append(self.queue.pop(0))
            n -= 1
        
        return self.queue.pop(0)


    def top(self) -> int:
        return self.queue[-1]


    def empty(self) -> bool:
        return len(self.queue) == 0

# 232. 用栈实现队列
class MyQueue:

    def __init__(self):
        self.stk1 = []
        self.stk2 = []


    def push(self, x: int) -> None:
        self.stk1.append(x)

    def pop(self) -> int:
        # 先调⽤ peek 保证 s2 ⾮空
        self.peek()
        return self.stk2.pop()


    def peek(self) -> int:
        if not self.stk2:
            while self.stk1:
                self.stk2.append(self.stk1.pop())

        return self.stk2[-1]


    def empty(self) -> bool:
        return len(self.stk2) == 0 and len(self.stk1) == 0


10-05 03:24