mirror of
https://github.com/Manoj-HV30/ds-lab-codes.git
synced 2026-05-16 19:35:22 +00:00
94 lines
1.4 KiB
C
94 lines
1.4 KiB
C
#include <stdbool.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
typedef struct {
|
|
int *keys;
|
|
int size;
|
|
int front;
|
|
int rear;
|
|
|
|
} cq;
|
|
|
|
cq *createqueue(int size) {
|
|
cq *q = (cq *)malloc(sizeof(cq));
|
|
q->size = size;
|
|
q->front = -1;
|
|
q->rear = -1;
|
|
q->keys = (int *)malloc(size * sizeof(int));
|
|
return q;
|
|
}
|
|
|
|
bool isFull(cq *q) { return ((q->rear + 1) % q->size == q->front); }
|
|
bool isEmpty(cq *q) { return q->front == -1; }
|
|
|
|
void enqueue(cq *q, int v) {
|
|
if (isFull(q)) {
|
|
printf("is full");
|
|
}
|
|
if (isEmpty(q)) {
|
|
q->front = 0;
|
|
q->rear = 0;
|
|
} else {
|
|
q->rear = (q->rear + 1) % q->size;
|
|
}
|
|
q->keys[q->rear] = v;
|
|
}
|
|
|
|
int dequeue(cq *q) {
|
|
if (isEmpty(q)) {
|
|
printf("Queue is empty! Cannot delete.\n");
|
|
return -1;
|
|
}
|
|
int v = q->keys[q->front];
|
|
if (q->front == q->rear) {
|
|
q->front = q->rear = -1;
|
|
|
|
} else {
|
|
q->front = (q->front + 1) % q->size;
|
|
}
|
|
return v;
|
|
}
|
|
|
|
void display(cq *q) {
|
|
if (isEmpty(q)) {
|
|
printf("Queue is empty!\n");
|
|
return;
|
|
}
|
|
int i = q->front;
|
|
while (1) {
|
|
printf("%d", q->keys[i]);
|
|
if (i == q->rear) {
|
|
break;
|
|
}
|
|
i = (i + 1) % q->size;
|
|
}
|
|
}
|
|
int main() {
|
|
int n;
|
|
printf("Enter size of queue: ");
|
|
scanf("%d", &n);
|
|
|
|
cq *q = createqueue(n);
|
|
|
|
enqueue(q, 10);
|
|
enqueue(q, 20);
|
|
enqueue(q, 30);
|
|
display(q);
|
|
|
|
dequeue(q);
|
|
display(q);
|
|
|
|
enqueue(q, 40);
|
|
enqueue(q, 50);
|
|
display(q);
|
|
|
|
dequeue(q);
|
|
display(q);
|
|
|
|
free(q->keys);
|
|
free(q);
|
|
|
|
return 0;
|
|
}
|