Stack 2개로 Queue 구현 with Python

팡팡·2021년 10월 31일

CS

목록 보기
3/6

릿코드로 구현해보기

class MyQueue:

    def __init__(self):
        self.main_stack = []
        self.sub_stack = []

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

    def pop(self) -> int:
        self.peek()
        return self.sub_stack.pop()

    def peek(self) -> int:
        if not self.sub_stack :
            while self.main_stack:
                self.sub_stack.append(self.main_stack.pop())
                
        return self.sub_stack[-1]

    def empty(self) -> bool:
        return not self.main_stack and not self.sub_stack

main_stack에 데이터를 집어놓는다.

만약 pop 이나 peek의 명령어가 들어올 경우 sub_stack 안에 데이터가 있는 경우와 없는 경우로 나뉜다.

  1. 없는 경우)
    데이터가 반드시 들어왔다는 가정 하에 main_stack에서 데이터를 반대로 집어넣는다.
  2. 있는 경우)
    기존 데이터를 바로 출력해야한다.

0개의 댓글