Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".
One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.
Your implementation should support following operations:
class MyCircularQueue:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the queue to be k.
"""
self.q = [None] * k # 배열에다가 None으로 채워줌으로써 크기를 결정
self.maxlen = k
self.head = 0 # 배열의 맨첫번째요소 포인터
self.tail = 0 # 배열의 마지막요소 포인터
def enQueue(self, value: int) -> bool:
"""
Insert an element into the circular queue. Return true if the operation is successful.
"""
if self.q[self.tail] is None:
self.q[self.tail] = value # 마지막 요소에 입력받은 값을 할당
self.tail = (self.tail + 1) % self.maxlen # 포인터의 위치가 전체길이보다 넘지 않게 하기위해서 전체길이로 나머지 연산
return True
else:
return False
def deQueue(self) -> bool:
"""
Delete an element from the circular queue. Return true if the operation is successful.
"""
if self.q[self.head] is None:
return False
else:
self.q[self.head] = None # 맨처음요소를 None으로 값을 주면서 값 삭제
self.head = (self.head + 1) % self.maxlen
return True
def Front(self) -> int:
"""
Get the front item from the queue.
"""
return -1 if self.q[self.head] is None else self.q[self.head]
def Rear(self) -> int:
"""
Get the last item from the queue.
"""
return -1 if self.q[self.tail -1] is None else self.q[self.tail - 1]
def isEmpty(self) -> bool:
"""
Checks whether the circular queue is empty or not.
"""
return self.q[self.head] == None and self.q[self.tail] == None
def isFull(self) -> bool:
"""
Checks whether the circular queue is full or not.
"""
return None not in self.q