본문 바로가기
Programming/LeetCode

[LeetCode] Implement Queue using Stacks(스택으로 큐 구현)

by 데이터현 2022. 3. 29.

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

스택을 두 개 사용해서 큐를 구현하는 문제

나의 풀이

class MyQueue:

    def __init__(self):
        self.s1 = list()
        self.s2 = list()

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

    def pop(self) -> int:
        if self.s2:
            return self.s2.pop()
        while self.s1:
            self.s2.append(self.s1.pop())
        return self.s2.pop()

    def peek(self) -> int:
        if self.s2:
            return self.s2[-1]
        elif self.s1:
            return self.s1[0]
        else:
            return None

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


# 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()

틀린 풀이는 아닌데, peek와 pop에서 단정하지 못한 느낌이 난다.

 

깔끔한 풀이

class MyQueue:

    def __init__(self):
        self.input = list()
        self.output = list()

    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 == []

댓글