Leetcode 232. 用栈实现队列 Implement Queue using Stacks - Python 用双栈实现队列

class MyQueue:

    def __init__(self):
        self.stack_in = []
        self.stack_out = []


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


    def pop(self) -> int:
        if self.empty():
            return None
        elif self.stack_out:
            return self.stack_out.pop()
        else:
            for i in range(len(self.stack_in)):
                self.stack_out.append(self.stack_in.pop())
            return self.stack_out.pop()

    def peek(self) -> int:
        if self.empty():
            return None
        ans = self.pop()
        self.stack_out.append(ans)
        return ans


    def empty(self) -> bool:
        return not (self.stack_in or self.stack_out)

思路:

stack_in = [1,2,3]

stack_out = []

stack_out.append( stack_in.pop() ) *3

stack_in = []

stack_out = [3.2.1]

stack_out.pop()

stack_out = [3,2]

你可能感兴趣的:(栈,队列,Leetcode刷题,leetcode,python)