본문 바로가기
Study/Algorithm

[LeetCode] #225. Implement Stack using Queues (python)

by 투말치 2022. 2. 24.
반응형

문제

https://leetcode.com/problems/implement-stack-using-queues/

 

Implement Stack using Queues - 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

큐를 사용해서 스택을 구현해야 한다.

push, top, pop, empty 기능을 구현하면 된다.

 

풀이

 

책 풀이

class MyStack:
    def __init__(self):
        self.q = collections.deque()

    def push(self, x):
        self.q.append(x)
        # 요소 삽입 후 맨 앞에 두는 상태로 재정렬
        for _ in range(len(self.q) - 1):
            self.q.append(self.q.popleft())

    def pop(self):
        return self.q.popleft()

    def top(self):
        return self.q[0]

    def empty(self):
        return len(self.q) == 0

책에서는 큐를 데크로 선언했다. 방금 추가한 요소를 맨 앞에 두기 위해 push에서 재정렬을 해준다.

나머지는 데크의 기본 연산으로 구할 수 있다.

 

 

참고한 책 : 파이썬 알고리즘 인터뷰

반응형