Solve problems involving circular queues in C

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_SIZE 5

typedef struct {
    int items[MAX_SIZE];
    int front;
    int rear;
    int size;
} CircularQueue;

// Initialize the circular queue
void initQueue(CircularQueue *q) {
    q->front = -1;
    q->rear = -1;
    q->size = 0;
}

// Check if the queue is empty
bool isEmpty(CircularQueue *q) {
    return q->size == 0;
}

// Check if the queue is full
bool isFull(CircularQueue *q) {
    return q->size == MAX_SIZE;
}

// Add an element to the queue (enqueue)
void enqueue(CircularQueue *q, int value) {
    if (isFull(q)) {
        printf("Queue is full. Cannot enqueue %d.\n", value);
        return;
    }
    
    if (isEmpty(q)) {
        q->front = 0;
    }
    
    q->rear = (q->rear + 1) % MAX_SIZE;
    q->items[q->rear] = value;
    q->size++;
    printf("Enqueued %d\n", value);
}

// Remove an element from the queue (dequeue)
int dequeue(CircularQueue *q) {
    if (isEmpty(q)) {
        printf("Queue is empty. Cannot dequeue.\n");
        return -1;
    }
    
    int item = q->items[q->front];
    if (q->front == q->rear) {
        // Queue has only one element, reset after removal
        q->front = -1;
        q->rear = -1;
    } else {
        q->front = (q->front + 1) % MAX_SIZE;
    }
    q->size--;
    printf("Dequeued %d\n", item);
    return item;
}

// Get the front element without removing it
int peek(CircularQueue *q) {
    if (isEmpty(q)) {
        printf("Queue is empty.\n");
        return -1;
    }
    return q->items[q->front];
}

// Display the queue
void display(CircularQueue *q) {
    if (isEmpty(q)) {
        printf("Queue is empty.\n");
        return;
    }
    
    printf("Queue elements: ");
    int i = q->front;
    int count = 0;
    
    while (count < q->size) {
        printf("%d ", q->items[i]);
        i = (i + 1) % MAX_SIZE;
        count++;
    }
    printf("\n");
}

int main() {
    CircularQueue q;
    initQueue(&q);
    
    enqueue(&q, 10);
    enqueue(&q, 20);
    enqueue(&q, 30);
    enqueue(&q, 40);
    enqueue(&q, 50);
    
    display(&q);
    
    // This will fail because queue is full
    enqueue(&q, 60);
    
    dequeue(&q);
    dequeue(&q);
    
    display(&q);
    
    enqueue(&q, 60);
    enqueue(&q, 70);
    
    display(&q);
    
    printf("Front element: %d\n", peek(&q));
    
    return 0;
}

Output:


Comments