Aim: Implement queue operations using linked list in C
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *front;
struct node *rear;
void insert();
void dequeue();
void display();
void main ()
{
int choice;
printf("\nQUEUE OPERATIONS USING LINKED LIST");
printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\n4.Exit");
while(choice != 4)
{
printf("\nEnter your choice ?");
scanf("%d",& choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nEnter valid choice\n");
}
}
}
void insert()
{
struct node *ptr;
int item;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW\n");
return;
}
else
{
printf("\nEnter value : ");
scanf("%d",&item);
ptr -> data = item;
if(front == NULL)
{
front = ptr;
rear = ptr;
front -> next = NULL;
rear -> next = NULL;
}
else
{
rear -> next = ptr;
rear = ptr;
rear->next = NULL;
}
}
}
void dequeue()
{
struct node *ptr;
if(front == NULL)
{
printf("\nUNDERFLOW\n");
return;
}
else
{
ptr = front;
front = front -> next;
free(ptr);
}
}
void display()
{
struct node *ptr;
ptr = front;
if(front == NULL)
{
printf("\nEmpty queue\n");
}
else
{ printf("\nElements in the queue are : \n");
while(ptr != NULL)
{
printf("\n%d\n",ptr -> data);
ptr = ptr -> next;
}
}
}
Output
QUEUE OPERATIONS USING LINKED LIST 1.insert an element 2.Delete an element 3.Display the queue 4.Exit Enter your choice ?1 Enter value : 5 Enter your choice ?1 Enter value : 6 Enter your choice ?1 Enter value : 7 Enter your choice ?1 Enter value : 8 Enter your choice ?3 Elements in the queue are : 5 6 7 8 Enter your choice ?2 Enter your choice ?3 Elements in the queue are : 6 7 8 Enter your choice ?4
