A circular queue is a fundamental data structure in computer science that operates based on the principle of the First-In-First-Out (FIFO) approach. Unlike a linear queue, a circular queue handles efficient memory utilization by reusing the vacant spaces. Implementing a circular queue in C involves creating an array-based structure and utilizing pointers to manage insertion, deletion, and traversal operations.
Understanding the Circular Queue
A circular queue comprises a fixed-size array and two pointers – front
and rear
. The front
pointer indicates the front element, while the rear
pointer denotes the rear or last element in the queue. When the queue is full, the rear
pointer points to the last element, and the next insertion occurs at the beginning of the array if space is available, creating a circular structure.
Implementing the Circular Queue in C
Below is a sample code illustrating the implementation of a circular queue in C
#include <stdio.h>
#define MAX_SIZE 5
int queue[MAX_SIZE];
int front = -1, rear = -1;
int isEmpty() {
return (front == -1 && rear == -1);
}
int isFull() {
return ((rear + 1) % MAX_SIZE == front);
}
void enqueue(int value) {
if (isFull()) {
printf("Queue is full. Cannot enqueue.\n");
return;
} else if (isEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % MAX_SIZE;
}
queue[rear] = value;
}
void dequeue() {
if (isEmpty()) {
printf("Queue is empty. Cannot dequeue.\n");
return;
} else if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX_SIZE;
}
}
void display() {
if (isEmpty()) {
printf("Queue is empty.\n");
return;
}
printf("Circular Queue elements: ");
int i = front;
while (i != rear) {
printf("%d ", queue[i]);
i = (i + 1) % MAX_SIZE;
}
printf("%d\n", queue[rear]);
}
void main() {
enqueue(1);
enqueue(12);
enqueue(3);
enqueue(14);
enqueue(53);
display(); // Output: 1 2 3 4 5
dequeue();
dequeue();
display(); // Output: 3 4 5
}
Output
The implementation of a circular queue in C demonstrates a practical approach to managing a data structure that optimizes memory utilization and efficiently handles data elements. Understanding and implementing such fundamental data structures is crucial for any programmer or computer science enthusiast, contributing to the core knowledge of data management and algorithms in programming languages like C.