implementation of circular queue using python lists circular fifo queue with a fixed capacity def initself n int self n n self array none self n self front 0 index of the first element self rear 0 self size 0 def lenself int return self size def isemptyself bool return self size 0 def firstself return false if self isempty else self arrayself front def enqueueself data if self size self n raise exceptionqueue is full self arrayself rear data self rear self rear 1 self n self size 1 return self def dequeueself if self size 0 raise exceptionunderflow temp self arrayself front self arrayself front none self front self front 1 self n self size 1 return temp implementation of circular queue using python lists circular fifo queue with a fixed capacity index of the first element cq circularqueue 5 len cq 0 cq enqueue a doctest ellipsis data_structures queue circular_queue circularqueue object at len cq 1 cq circularqueue 5 cq is_empty true cq enqueue a is_empty false cq circularqueue 5 cq first false cq enqueue a first a this function insert an element in the queue using self rear value as an index cq circularqueue 5 cq enqueue a doctest ellipsis data_structures queue circular_queue circularqueue object at cq size cq first 1 a cq enqueue b doctest ellipsis data_structures queue circular_queue circularqueue object at cq size cq first 2 a this function removes an element from the queue using on self front value as an index cq circularqueue 5 cq dequeue traceback most recent call last exception underflow cq enqueue a enqueue b dequeue a cq size cq first 1 b cq dequeue b cq dequeue traceback most recent call last exception underflow
class CircularQueue:
    

    def __init__(self, n: int):
        self.n = n
        self.array = [None] * self.n
        self.front = 0  
        self.rear = 0
        self.size = 0

    def __len__(self) -> int:
        
        return self.size

    def is_empty(self) -> bool:
        
        return self.size == 0

    def first(self):
        
        return False if self.is_empty() else self.array[self.front]

    def enqueue(self, data):
        
        if self.size >= self.n:
            raise Exception("QUEUE IS FULL")

        self.array[self.rear] = data
        self.rear = (self.rear + 1) % self.n
        self.size += 1
        return self

    def dequeue(self):
        
        if self.size == 0:
            raise Exception("UNDERFLOW")

        temp = self.array[self.front]
        self.array[self.front] = None
        self.front = (self.front + 1) % self.n
        self.size -= 1
        return temp