C PROGRAMMINGDATA STRUCTURES

queue using linked list

queue using linked list

A queue is a linear data structure where elements are inserted from one end and deleted from other end. Element are inserted for rare and deleted from front of the queue.
There are two types of operations performed on queues 
Enqueue                     Dequeue

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct node
{
int data;
struct node *link;
};
struct node *front=NULL;
struct node *rear=NULL;

void enque(int data)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=data;
temp->link=NULL;
if(rear==NULL)
{
front=temp;
rear=temp;
}
else
{
rear->link=temp;
rear=temp;
}
printf("%d enqued in Queuen",data);
}

void deque()
{
struct node *cur=front;
if(front==NULL)
{
printf("n Queue is Empty ");
return;
}
printf("%d dequed from Queuen",front->data);
if(front==rear)
{
front=NULL;
rear=NULL;
}
else
front=front->link;
free(cur);
}


void display()
{
struct node *cur;
cur = front;
if(front == NULL)
{
printf("n-----------------------------------------------------------------------");
printf("nnQueue is emptyn");
printf("n--------------------------------------------------------------------------");
}
else
{
printf("nn---------------------- Queue --------------------------------nn");
printf("Contentsnn");
while(cur != NULL)
{
printf("%dnn",cur->data);
cur = cur->link;
}
}
}

void main()
{
int option, val;
do
{
printf("n *****MENU*****");
printf("n 1. Enque");
printf("n 2. Deque");
printf("n 3. DISPLAY");
printf("n 0. EXIT");
printf("n Enter your choice: ");
scanf("%d",&option);
switch(option)
{
case 1:
printf("n Enter the value to enque into Queue: ");
scanf("%d",&val);
enque(val);
break;
case 2:
deque();
break;
case 3:
display();
break;
case 0:
printf("nExiting...");
exit(0);
break;
default:
printf("nInvalid option. Try again...");
}

}while(1);
getch();
}

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button