Page

How to Implement Enqueue & Dequeue using Linked List

#include<stdio.h>
#include<conio.h>
struct queue
{
int d1;
int p1;
struct queue *link1;
};
struct queue *ptr1,*front1=NULL,*temp1;
struct queue2
{
int d2;
int p2;
struct queue2 *link2;
};
struct queue2 *ptr2,*front2=NULL,*temp2;
void main()
{
int ch;
clrscr();
while(1)
{
printf("\n\n1-ENQUEUE.");
printf("\n2-DEQUEUE.");
printf("\n3-DISPLAY.");
printf("\n4-EXIT.");
printf("\nEnter your choice(1-4): ");
scanf("%d",&ch);
switch(ch)
{
case 1:
temp1=(struct queue*)malloc(sizeof(struct queue));
printf("Enter the element: ");
scanf("%d",&temp1->d1);
printf("Enter it's priority: ");
scanf("%d",&temp1->p1);
if(front1==NULL||temp1->p1<front1->p1)
{
temp1->link1=front1;
front1=temp1;
}
else
{
ptr1=front1;
while(ptr1->link1!=NULL&&ptr1->link1->p1<=temp1->p1)
ptr1=ptr1->link1;
temp1->link1=ptr1->link1;
ptr1->link1=temp1;
}
break;
case 2:
if(front1==NULL)
{
printf("\nQueue is underflow.");
}
else
{
temp2=(struct queue2*)malloc(sizeof(struct queue2));
temp2->d2=front1->d1;
temp2->p2=front1->p1;
if(front2==NULL||temp2->p2<front2->p2)
{
temp2->link2=front2;
front2=temp2;
}
else
{
ptr2=front2;
while(ptr2->link2!=NULL&&ptr2->link2<=temp2->p2)
ptr2=ptr2->link2;
temp2->link2=ptr2->link2;
ptr2->link2=temp2;
}
temp1=front1;
front1=front1->link1;
free(temp1);
}
break;
case 3:
clrscr();
printf("\nFrist queue:\n");
ptr1=front1;
printf("\n[%u]->\n\t",front1);
while(ptr1!=NULL)
{
printf("->[%d:%d:%u]",ptr1->d1,ptr1->p1,ptr1->link1);
ptr1=ptr1->link1;
}
printf("\nSecond  queue:\n");
ptr2=front2;
printf("\n[%u]->\n\t",front2);
while(ptr2!=NULL)
{
printf("->[%d:%d:%u]",ptr2->d2,ptr2->p2,ptr2->link2);
ptr2=ptr2->link2;
}
break;
case 4:
exit(0);
default:printf("\nInvalid choice.");
}
}
getch();
}

No comments:

Post a Comment