본문 바로가기
Programming/LeetCode

[LeetCode] Implement Stack using Queues(큐로 스택 구현)

by 데이터현 2022. 3. 29.

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 할 때 append 해주고 기존에 queue에 있던 원소는 popleft 이후 다시 큐의 맨 뒤로 줄줄이 붙여주면 된다.

요소 삽입 시 시간복잡도가 O(N)이 되어 다소 비효율적이긴 하지만, 큐로 스택을 구현할 수 있다.

class MyStack:

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

    def push(self, x: int) -> None:
        self.q.append(x)
        for _ in range(len(self.q) - 1):
            self.q.append(self.q.popleft())
            
    def pop(self) -> int:
        return self.q.popleft()

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

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


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

댓글