Technical Interview Question: Design a circular queue using a doubly linked list in a programming language of your choice. The circular queue should support operations such as enqueuing, dequeuing, checking if the queue is full or empty, and displaying the elements of the queue.
Answer:
# Node class for the doubly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# CircularQueue class to implement the circular queue using the doubly linked list
class CircularQueue:
def __init__(self, k):
self.capacity = k
self.size = 0
self.head = None
self.tail = None
# Method to enqueue an element into the circular queue
def enQueue(self, value):
if self.isFull():
return False
new_node = Node(value)
if self.isEmpty():
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
new_node.prev = self.tail
self.head.prev = new_node
new_node.next = self.head
self.tail = new_node
self.size += 1
return True
# Method to dequeue an element from the circular queue
def deQueue(self):
if self.isEmpty():
return False
if self.size == 1:
self.head = None
self.tail = None
else:
self.head = self.head.next
self.head.prev = self.tail
self.tail.next = self.head
self.size -= 1
return True
# Method to check if the circular queue is empty
def isEmpty(self):
return self.size == 0
# Method to check if the circular queue is full
def isFull(self):
return self.size == self.capacity
# Method to display the elements of the circular queue
def display(self):
if self.isEmpty():
print("Queue is empty")
else:
current = self.head
while True:
print(current.data, end=" ")
current = current.next
if current == self.head:
break
print()
# Example usage
cq = CircularQueue(5)
cq.enQueue(1)
cq.enQueue(2)
cq.enQueue(3)
cq.display() # Output: 1 2 3
cq.deQueue()
cq.display() # Output: 2 3
cq.enQueue(4)
cq.enQueue(5)
cq.enQueue(6) # Output: Queue is full
In this example, we have designed a circular queue using a doubly linked list in Python. The CircularQueue class provides methods for enqueuing, dequeuing, checking if the queue is full or empty, and displaying the elements of the queue. The key operations have been implemented such that they maintain the circular nature of the queue using the properties of the doubly linked list.