본문 바로가기
Study/Algorithm

[LeetCode] #232. Implement Queue using Stacks (python)

by 투말치 2022. 2. 24.
반응형

문제

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

스택을 사용해서 큐를 구현하는 문제다.

 

예시 입출력

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]

Output
[null, null, null, 1, 1, false]

 

 

풀이

 

내 풀이

class MyQueue:

    def __init__(self):
        self.s1=[]

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

    def pop(self) -> int:
        return self.s1.pop(0)

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

    def empty(self) -> bool:
        return len(self.s1)==0

 

책 풀이

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

    def push(self, x):
        self.input.append(x)

    def pop(self):
        self.peek()
        return self.output.pop()

    def peek(self):
        # output이 없으면 모두 재입력
        if not self.output:
            while self.input:
                self.output.append(self.input.pop())
        return self.output[-1]

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

pop을 할 때는 peek을 실행해서 output이 없으면 input을 pop해서 output에 추가한다. 그러면 output의 맨 뒤에는 큐의 첫번째 데이터가 들어있게 된다.

 

 

참고한 책 : 파이썬 알고리즘 인터뷰

반응형