Open In App

Circular Queue in Python

Last Updated : 12 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A Circular Queue is a kind of queue that can insert elements inside it dynamically. Suppose, in a given array there is not any space left at the rare but we have space at the front in the normal queue it is not possible to insert elements at the front but in the case of a circular queue we can do that. So in this case, once the array is full till the last space then we insert the further elements at the front if there is any space left. That’s why it is known as a circular queue.

Operations on Circular Queue:

  • Front: Get the front item from the queue.
  • Rear: Get the last item from the queue.
  • enQueue(value) This function is used to insert an element into the circular queue. In a circular queue, the new element is always inserted at the rear position. 
    • Check whether the queue is full – [i.e., the rear end is in just before the front end in a circular manner].
    • If it is full then display Queue is full. 
      • If the queue is not full then,  insert an element at the end of the queue.
  • deQueue() This function is used to delete an element from the circular queue. In a circular queue, the element is always deleted from the front position. 
    • Check whether the queue is Empty.
    • If it is empty then display Queue is empty.
      • If the queue is not empty, then get the last element and remove it from the queue.

Implementation of Circular Queue in Python

In a normal queue, we keep on adding the elements at the rear of the array and once we reach the end of the array we will not be able to insert the elements further. To get rid of this problem we can use the spaces available at the front which is created while removing elements from the queue. We will use the following method to implement the circular queue.

  1. When we insert the element in the queue we will increment the index by (index+1)%size instead of just adding one to it.
  2. This will ensure that when we reach the end of the array the index will move again to the start of the array.
  3. Now check if the space is empty or not. If the space is empty we can insert the elements further in it.
  4. In this method we are inserting elements circularly that’s why this method is called circular queue.

Code:

Python
class CircularQueue:
    def __init__(self, size):
        self.maxSize = size
        self.queueArray = [0] * size
        self.front = -1
        self.rear = -1

    def enqueue(self, item):
        if self.isEmpty():
            self.front = 0
            self.rear = 0
            self.queueArray[self.rear] = item
        else:
            self.rear = (self.rear + 1) % self.maxSize
            if self.rear == self.front:
                print("Queue is full. Cannot enqueue.")
                self.rear = (self.rear - 1 + self.maxSize) % self.maxSize
            else:
                self.queueArray[self.rear] = item

    def dequeue(self):
        item = -1  # Assuming -1 represents an empty value

        if not self.isEmpty():
            item = self.queueArray[self.front]
            if self.front == self.rear:
                self.front = -1
                self.rear = -1
            else:
                self.front = (self.front + 1) % self.maxSize
        else:
            print("Queue is empty. Cannot dequeue.")

        return item

    def peek(self):
        if not self.isEmpty():
            return self.queueArray[self.front]
        else:
            print("Queue is empty. No peek value.")
            return -1  # Assuming -1 represents an empty value

    def isEmpty(self):
        return self.front == -1 and self.rear == -1


if __name__ == "__main__":
    circularQueue = CircularQueue(5)

    circularQueue.enqueue(1)
    circularQueue.enqueue(2)
    circularQueue.enqueue(3)

    # Should print 1
    print("Peek:", circularQueue.peek())

    # Should print 1
    print("Dequeue:", circularQueue.dequeue())

    # Should print 2
    print("Peek after dequeue:", circularQueue.peek())

Output
('Peek:', 1)
('Dequeue:', 1)
('Peek after dequeue:', 2)

Time complexity Circular Queue in Python:

  • Enqueue: O(1)
  • Dequque: O(1)
  • Peek: O(1)
  • isEmpty: O(1)

Auxiliary Space complexity Circular Queue in Python:

  • O(N)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads