[LeetCode] Implement Queue using Stacks (Python)

2024. 3. 8. 10:43알고리즘

 

 

class MyQueue:

    def __init__(self):
        self.stack_input = []
        self.stack_output = []

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

    def pop(self) -> int:
        length = len(self.stack_input) - 1
        for _ in range(length):
            self.stack_output.append(self.stack_input.pop())
        front = self.stack_input.pop()
        for _ in range(length):
            self.stack_input.append(self.stack_output.pop())
        return front

    def peek(self) -> int:
        return self.stack_input[0]

    def empty(self) -> bool:
        if self.stack_input:
            return False
        return True


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()