Circular Queue implementation in C
Circular queue is a type of queue in which both of the end wrapped together to form a circle. It has two pointers rear and front.
Features:
- It follows FIFO principle.
- Front points the element to be dequeued.
- Rear points the last inserted element.
- Functions in the circular Queue:
- ‘isFull()’ – Checks for queue is full or not.
- ‘isEmpty()’-Checks for emptiness.
- ‘peek()’ -View the front element without deleting.
- ‘Dequeue()’ – Deletes the front element.
- ‘Enqueue()’ – Inserts the value to the queue.
#include <stdio.h>
#define SIZE 6
int c_queue[SIZE];
int cq_front = -1, cq_rear = -1;
// Check the queue is full or not
int isFull() {
return (cq_front
== (cq_rear + 1) % SIZE);
}
// Check the queue is empty or not
int isEmpty() {
return (cq_front
== -1);
}
// Add elements to the queue
void enqueue(int element) {
if (isFull()) {
printf("Queue is full\n");
} else {
if (cq_front
== -1) cq_front = 0;
cq_rear =
(cq_rear + 1) % SIZE;
c_queue[cq_rear] = element;
printf("%d enqueued\n", element);
}
}
// Remove element from the queue
void dequeue() {
if (isEmpty()) {
printf("Queue is empty\n");
} else {
printf("%d dequeued\n",c_queue[cq_front]);
if (cq_front
== cq_rear) {
cq_front =
cq_rear = -1;
} else {
cq_front =
(cq_front + 1) % SIZE;
}
}
}
// Display the queue elements
void display() {
if (isEmpty()) {
printf("Queue is empty\n");
} else {
printf("Queue elements: ");
int i =
cq_front;
while (1) {
printf("%d ", c_queue[i]);
if (i ==
cq_rear) break;
i = (i +
1) % SIZE;
}
printf("\n");
}
}
int main() {
enqueue(100);
enqueue(210);
enqueue(30);
enqueue(420);
display();
dequeue();
display();
enqueue(76);
enqueue(87);
display();
return 0;
}
Output:
100 enqueued
210 enqueued
30 enqueued
420 enqueued
Queue elements: 100 210 30 420
100 dequeued
Queue elements: 210 30 420
76 enqueued
87 enqueued
Queue elements: 210 30 420 76 87
The code implementation of circular queue was successful.
Keep coding!!!
Comments
Post a Comment