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


풀이 과정

스택을 사용해 큐를 구현하는 문제이다.

 

큐를 스택으로 구현하는데엔 2개의 스택이 필요하다. push때는 스택에 넣고, pop이나 맨 위의 원소를 뽑아야 할 때는 스택의 원소를 다른 스택에 모두 넣어서 스택의 원소의 순서를 모두 뒤집고 스택 탑에 접근해서 큐를 구현할 수 있다.


소스 코드

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

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

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

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

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

+ Recent posts