📊알고리즘, 문제풀이/📈문제풀이 (PS)

[알고리즘][Python] LeetCode 232 Implement Queue Using Stacks 문제 풀이

Written by Donghak Park

문제 출처 : 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


문제 해석 : Stack을 이용해서 Queue를 구현 하는 문제이다.

 

문제 풀이 : 다른 기능들은 쉽게 구현 할 수 있지만 pop을 수행 할때는 순서에 유의해서 temp 배열에 저장하고 원하는 값을 꺼낸뒤에 다시 원상태로 복귀 시켜줘야 한다.


풀이 코드

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

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

    def pop(self) -> int:
        temp = []
        while len(self.Q) > 1:
            temp.append(self.Q.pop())
        ret = self.Q.pop()
        while temp:
            self.Q.append(temp.pop())
        return ret

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

    def empty(self) -> bool:
        if len(self.Q) == 0:
            return True
        else:
            return False

author : donghak park
contact : donghark03@naver.com

## 문제의 저작권은 LeetCode 사이트에 있습니다. 혹시 문제가 되는 부분이 있으면 연락 바랍니다.