关于数据结构与算法:每日leetcode232-用栈实现队列

2次阅读

共计 694 个字符,预计需要花费 2 分钟才能阅读完成。

题目

请你仅应用两个栈实现先入先出队列。队列该当反对个别队列反对的所有操作(push、pop、peek、empty)

思路

应用两个栈,stack_in 栈模仿队列 push,stack_out 栈模仿队列 pop
pop 时,如果 stack_out 空栈,将 stack_in 栈顺次 pop 到 stack_out 中
而后 stack_out 再 pop

class MyQueue:

    def __init__(self):
        # 应用两个栈,stack_in 栈模仿队列 push,stack_out 栈模仿队列 pop
        # pop 时,如果 stackstack_out 空栈,将 stack_in 栈顺次 pop 到 stack_out 中
        # 而后 stack_out 再 pop
        self.stack_in = []
        self.stack_out = []

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

    def pop(self) -> int:
        if not self.stack_out:
            while self.stack_in:
                self.stack_out.append(self.stack_in.pop())
        return self.stack_out.pop()

    def peek(self) -> int:
        if not self.stack_out:
            while self.stack_in:
                self.stack_out.append(self.stack_in.pop())
        return self.stack_out[-1]

    def empty(self) -> bool:
        return not self.stack_in and not self.stack_out
正文完
 0