Day 8 of DSA in C
Write a menu driven C program to create a queue using linked list and perform basic functions on it.
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
struct Node {
int data;
struct Node* next;
};
struct Node* front = NULL;
struct Node* rear = NULL;
int count = 0;
void enqueue(int value) {
if (count == MAX) {
printf("Queue Overflow! (limit %d)\n", MAX);
return;
}
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation failed!\n");
return;
}
newNode->data = value;
newNode->next = NULL;
if (rear == NULL) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
count++;
printf("Enqueued %d into queue.\n", value);
}
void dequeue() {
if (front == NULL) {
printf("Queue Underflow!\n");
return;
}
struct Node* temp = front;
printf("Dequeued %d from queue.\n", temp->data);
front = front->next;
if (front == NULL) rear = NULL;
free(temp);
count--;
}
void display() {
if (front == NULL) {
printf("Queue is empty!\n");
return;
}
struct Node* temp = front;
printf("Queue elements: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
int choice, value;
while (1) {
printf("\n---- QUEUE MENU ----\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value: ");
scanf("%d", &value);
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice! Try again.\n");
}
}
return 0;
}
Comments