본문 바로가기

그 땐 Algorithm했지/그 땐 Python했지

[TAVE/파이썬 알고리즘] Ch9 | 스택, 큐 - 24번 스택을 이용한 큐 구현

728x90

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

 

Implement Queue using Stacks - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

스택 2개 이용
class MyQueue:

    def __init__(self):
        self.input = []
        self.output = []
        

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

    def pop(self) -> int:
        self.peek()
        return self.output.pop()
        

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

    def empty(self) -> bool:
        return self.input = [] and self.output = []

 

👉🏻스택은 맨 뒤의 아이템을 끄집어내야하므로 하나의 스택으로는 풀이가 불가능하다. 2개의 스택을 이용한다.

👉🏻pop()과 peek()은 결국 같은 데이터를 끄집어내는 것이므로 pop()할 때 peek()을 호출하고 재입력하도록 알고리즘을 구현한다.

✍🏻output의 값이 모두 pop()되기 전까지 다시 재입력이 일어나지 않으므로 분할 상환 분석에 따른 시간 복잡도는 여전히 O(1)이다.

728x90