본문 바로가기
IT/알고리즘

[Leetcode]232. Implement Queue using Stacks

by 어센트 2020. 10. 6.

Implement Queue using Stacks - LeetCode

 

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