//queue linked list
//header files
#include <stdio.h>
#include <stdlib.h>
// Define a structure for a node in the queue.
struct node
{
int data;
struct node *next;
};
// Declare global pointers for the front and rear of the queue.
struct node *front;
struct node *rear;
// Function prototypes.
void insert();
void delete();
void display();
int main()//main starts
{
int choice;
// Initialize front and rear pointers to NULL.
front = rear = NULL;
// Main menu loop.
while (choice != 4)
{
printf("1. Insert an element\n2. Delete an element\n3. Display the queue\
n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();//insertion
break;
case 2:
delete();//deletion
break;
case 3:
display();//dispay queue
break;
case 4:
exit(0);
break;
default://default case
printf("Enter a valid choice.\n");
}
}
return 0;
}
// Function to insert an element into the queue.
void insert()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));//memory allocation
if (ptr == NULL)//checking whether the queue is full
{
printf("OVERFLOW: Unable to allocate memory.\n");
return;
}
else//if queue isnt full this executes
{
printf("Enter a value: ");
scanf("%d", &item);
ptr->data = item;
if (front == NULL)
{
// If the queue is empty, set both front and rear to the new node.
front = ptr;
rear = ptr;
front->next = NULL;
rear->next = NULL;
}
else
{
// If the queue is not empty, add the new node to the rear.
rear->next = ptr;
rear = ptr;
rear->next = NULL;
}
}
}
// Function to delete an element from the queue.
void delete()
{
struct node *ptr;
if (front == NULL)//checking if queue is empty
{
printf("UNDERFLOW: Queue is empty.\n");
return;
}
else
{
ptr = front;
front = front->next;
free(ptr);//deallocating memory
}
}
// Function to display the elements in the queue.
void display()
{
struct node *ptr;
ptr = front;
if (front == NULL)//checking weather queue is empty
{
printf("Empty queue.\n");
}
else
{
printf("Printing values:\n");
while (ptr != NULL)
{
printf("%d\n", ptr->data);
ptr = ptr->next;
}
}
}