LC 0622 [M] Design Circular Queue - ALawliet/algorithms GitHub Wiki
we just need headIndex and the rest can be derived:
enqueue: (headIndex + n) % k
dequeue: (headIndex + 1) % k
tailIndex = (headIndex + n - 1) % k
class MyCircularQueue:
def __init__(self, k: int):
self.q = [0] * k
self.headIndex = 0
self.n = 0
self.k = self.capacity = k
def enQueue(self, value: int) -> bool:
if self.n == self.k:
return False
nextHeadIndex = (self.headIndex + self.n) % self.k
self.q[nextHeadIndex] = value # set the value at next available spot
self.n += 1
return True
def deQueue(self) -> bool:
if not self.n:
return False
nextHeadIndex = (self.headIndex + 1) % self.k
self.headIndex = nextHeadIndex # just move the head forward
self.n -= 1
return True
def Front(self) -> int: # where is the current head?
if not self.n:
return -1
return self.q[self.headIndex]
def Rear(self) -> int: # where is the current tail?
if not self.n:
return -1
tailIndex = (self.headIndex + self.n - 1) % self.k
return self.q[tailIndex]
def isEmpty(self) -> bool:
return not self.n
def isFull(self) -> bool:
return self.n == self.k
# 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()