Design a Circular Queue
Approach1: Array
Based on the description of the problem, an intuitive data structure that meets all the requirements would be a ring where the head and the tail are adjacent to each other.
Since there does not exist such data structure, we will use an array to simulate such behavior. I've also inserted a pictorial representation in the below.
Visual:
As seen in the below example, the below circular Queue is of a maximum capacity of 4.
Since we follow the FIFO properties in a Queue, Index 0 is empty due to a Deque operation being called.
The maximum capacity is 4 however it's current size is 3. In order to take advantage of the empty space, we need to access the first index.
Since we insert at the rear in a Queue, we use the below formula to access the 0th index.
Enque: (Rear + 1) % capacity
Since we dequeue from the front in a Queue
Deque: (Front + 1) % capacity

class MyCircularQueue:
def __init__(self, k: int):
self.capacity = k
self.size = 0
self.t = [0] * self.capacity
self.front, self.rear = 0, -1
def enQueue(self, value: int) -> bool:
if self.isFull(): return False
self.rear = (self.rear + 1) % self.capacity
self.t[self.rear] = value
self.size += 1
return True
def deQueue(self) -> bool:
if self.isEmpty(): return False
self.front = (self.front + 1) % self.capacity
self.size -= 1
return True
def Front(self) -> int:
if self.isEmpty(): return -1
return self.t[self.front]
def Rear(self) -> int:
if self.isEmpty(): return -1
return self.t[self.rear]
def isEmpty(self) -> bool:
return self.size == 0
def isFull(self) -> bool:
return self.size == self.capacity
Approach2: Linked List

class ListNode:
def __init__(self, value=-1, next=None):
self.value =value
self.next = next
class MyCircularQueue:
def __init__(self, k: int):
self.head = self.tail = None
self.size = 0
self.k = k
def enQueue(self, value: int) -> bool:
if self.isFull(): return False
node = ListNode(value)
if self.size == 0:
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
self.size += 1
return True
def deQueue(self) -> bool:
if self.isEmpty(): return False
self.head = self.head.next
self.size -= 1
return True
def Front(self) -> int:
return -1 if self.isEmpty() else self.head.value
def Rear(self) -> int:
return -1 if self.isEmpty() else self.tail.value
def isEmpty(self) -> bool:
return self.size == 0
def isFull(self) -> bool:
return self.size == self.k
Last updated
Was this helpful?