본문 바로가기
Programming/LeetCode

[LeetCode] Design Circular Queue (스택으로 원형 큐 구현)

by 데이터현 2022. 3. 29.

https://leetcode.com/problems/design-circular-queue/

 

Design Circular Queue - 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

투 포인터 개념으로 풀면 된다.

class MyCircularQueue:

    def __init__(self, k: int):
        self.q = [None]*k
        self.head = 0
        self.tail = 0
        self.size = k

    def enQueue(self, value: int) -> bool:
        if self.q[self.tail] is None:
            self.q[self.tail] = value
            self.tail = (self.tail + 1) % self.size
            return True
        return False

    def deQueue(self) -> bool:
        if self.q[self.head] is not None:
            self.q[self.head] = None
            self.head = (self.head + 1) % self.size
            return True
        return False
        

    def Front(self) -> int:
        return -1 if self.q[self.head] is None else self.q[self.head]

    def Rear(self) -> int:
        return -1 if self.q[self.tail - 1] is None else self.q[self.tail - 1]

    def isEmpty(self) -> bool:
        return self.head == self.tail and self.q[self.head] is None

    def isFull(self) -> bool:
        return self.head == self.tail and self.q[self.head] is not None     


# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()

댓글