Basic Operations on Circular Queue in C++
The basic operations of the circular queue are same as that of normal queue but the implementation is different. The following table list the basic operations in circular queue:
Operation | Description | Time Complexity | Space Complexity |
---|---|---|---|
Enqueue | This function is used to insert an element into the circular queue. | O(1) | O(1) |
Dequeue | This function is used to delete an element from the circular queue. | O(1) | O(1) |
Peek | Returns the front element of the queue. | O(1) | O(1) |
IsFull | Returns true is the queue is full otherwise returns false. | O(1) | O(1) |
IsEmpty | Returns true is the queue is empty otherwise returns false. | O(1) | O(1) |
Representation of Circular Queue in C++
The circular queue in C++ can be represented as a class which contains the rear and front index pointers, array to store queue elements, and the member functions to provide the basic operations.
class Queue {
private:
int front, rear;
int arr[MAX_SIZE];
public
........
}
Implementation of isEmpty for Circular Queue
The queue is only empty when the front == rear pointer
Algorithm of isEmpty
if front is equal to rear
return true
else
return false
Implementation of isFull for Circular Queue
The queue will be full when the incremented rear pointer is equal to the front pointer.
Algorithm of isFull
if (rear + 1) % size is equal to front
return true;
else
return false;
Implementation of Enqueue for Circular Queue
We insert the new elements at the end of the queue using rear pointer. We first check if the queue is full or not.
Algorithm of Enqueue
if (isFull(queue)) {
print "Queue Overflow"
return
else
rear = (rear + 1) % size
arr[rear] = new_element
Implementation of Dequeue for Circular Queue
The elements are removed from the queue at the front of the queue. We first need to check whether queue is empty or not.
Algorithm of Enqueue
if (isEmpty(queue)) {
print "Queue Underflow"
return
else
front = (front + 1) % size
C++ Program to Implement Circular Queue
In C++, Queues are a fundamental data structure in computer science which works on the principle of FIFO (First In, First Out). They can be implemented using both array and linked list. A circular queue is a type of queue in which the last element is connected to the first element, forming a circular structure. In this article, we’ll learn about circular queue, how to implement it in C++, and analyze its complexity.