Write a C Program to implement circular queue using dynamic memory allocation. Set the
initial capacity of the queue as 2. The capacity should double whenever the queue is Full.
Through proper output show insertion, deletion and doubling the size of the queue.
#include <stdio.h>
#include <stdbool.h>
struct queue {
int *data;
int front, rear;
int size;
int capacity;
};
bool queue_create(struct queue *q, size_t capacity) {
*q = (struct queue) {
.data = malloc(sizeof(int) * capacity),
.front = 0,
.rear = 0,
.size = 0,
.capacity = capacity
};
return q->data != NULL;
}
bool queue_is_full() {
return rear == capacity;
}
bool queue_is_empty() {
return size == 0;
}
bool queue_push(struct queue *q, int val) {
if (queue_is_full(q)) {
return false;
} else {
q->data[q->rear] = val;
q->rear = (q->rear + 1) % q->capacity;
q->size = (q->size + 1);
return true;
}
}
bool queue_pop(struct queue *q, int *ret) {
if (queue_is_empty(q)) {
return false;
} else {
*ret = q->data[q->front];
q->front = (q->front + 1) % q->capacity;
q->size = (q->size - 1);
return true;
}
}
void queue_remove(struct queue *q) {
if (q != NULL) {
free(q->date);
}
}
int main() {
}
Comments
Leave a comment