MIT-Curricular/DS/C/endsem-omnibus/circq.c

102 lines
2.2 KiB
C
Raw Normal View History

2024-11-20 08:29:16 +05:30
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int queue[MAX];
int front = -1;
int rear = -1;
// Different from normal queue: Need to check if (rear+1)%MAX == front for full condition
int isFull() {
if((rear + 1) % MAX == front)
return 1;
return 0;
}
// Different from normal queue: Both front and rear can wrap around to 0
int isEmpty() {
if(front == -1)
return 1;
return 0;
}
void enqueue() {
int item;
if(isFull()) {
printf("\nQueue is Full!!");
}
else {
printf("\nEnter element to insert: ");
scanf("%d", &item);
// Different from normal queue: rear wraps around using modulo
if(front == -1) {
front = rear = 0;
}
else {
rear = (rear + 1) % MAX;
}
queue[rear] = item;
printf("\nElement inserted successfully!");
}
}
void dequeue() {
if(isEmpty()) {
printf("\nQueue is Empty!!");
}
else {
printf("\nDeleted element is: %d", queue[front]);
// Different from normal queue: front wraps around using modulo
if(front == rear) {
front = rear = -1;
}
else {
front = (front + 1) % MAX;
}
}
}
void display() {
int i;
if(isEmpty()) {
printf("\nQueue is Empty!!");
}
else {
printf("\nQueue elements are: ");
// Different from normal queue: Need to use modulo to wrap around while displaying
for(i = front; i != rear; i = (i + 1) % MAX) {
printf("%d ", queue[i]);
}
printf("%d", queue[i]);
}
}
int main() {
int choice;
while(1) {
printf("\n\n1. Insert");
printf("\n2. Delete");
printf("\n3. Display");
printf("\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\nInvalid choice!!");
}
}
return 0;
}