Implement Queue using Stacks

https://leetcode.cn/problems/implement-queue-using-stacks/

push:
直接插入辅助栈

pop/peak:
1.如果数据栈有数据,直接出栈;
2.1.否则,如果辅助栈有数据,不停出栈给到数据栈
2.2.出栈数据栈中的元素

class MyQueue:
    def __init__(self):
        self._data = []
        self._helper = []

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

    def pop(self) -> int:
        if self._helper:
            return self._helper.pop()
        while len(self._data) > 0:
            self._helper.append(self._data.pop())
        return self._helper.pop()

    def peek(self) -> int:
        if self._helper:
            return self._helper[-1]
        while len(self._data) > 0:
            self._helper.append(self._data.pop())
        return self._helper[-1]

    def empty(self) -> bool:
        return len(self._data) == 0 and len(self._helper) == 0
posted @ 2022-11-06 11:15  7aughing  阅读(4)  评论(0编辑  收藏  举报