본문 바로가기

Algorithm/파이썬 알고리즘 인터뷰 스터디

[스택, 큐] 24 스택을 이용한 큐 구현(Implement Queue using Stacks) - 작성중

<LeetCode 문제>

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과 output 두 개의 스택을 이용해서 queue를 구현합니다.

output 스택에 아무것도 없는 상태에서 pop을 수행하려고 할 때 input 스택에 쌓여있는 값들을 전부 output 스택으로 이관시키는 것이 포인트입니다!

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.input=[]
        self.output=[]

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.input.append(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        self.peek() #output 비어있으면 input꺼 옮기기
        return self.output.pop()

    def peek(self) -> int:
        """
        Get the front element.
        """
        
        if not self.output: #output이 비어있으면
            while self.input:
                self.output.append(self.input.pop()) #output으로 다 옮기기
                
        return self.output[-1]
        

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return len(self.input)==0 or len(self.output)==0 #input, output 모두빌때


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

<학습내용>

1.

<학습이 필요한 내용>

1. pop, peek 차이