Priority Queue Sorting in C Type 2 (Unsorted Queue)

Description

2. This program is used to insert element in a queue, deletion is done according to the priority assigned, element with the highest priority will be dequeued first 

Note : In this program elements are en queued in any order independent of the priority assigned, dequeue is done according to the priority.


#include<stdio.h>
#include<stdlib.h>
#define MAX 5
void enqueue();
void dequeue();
void display();
struct node
{
 int data;
 int priority;
 struct node * next;
};
struct node * head=NULL;
int count = 0;


main()
{
 int choice;
 do
 {
  printf("\n----MENU----\n");
  printf("1.enqueue\n2.dequeue\n3.display\n4.EXIT\n");
  printf("\nEnter your choice\n");
  scanf("%d",&choice);
  switch(choice)
  {
   case 1:enqueue();break;
   case 2:dequeue();break;
   case 3:display();break;
   case 4:printf("\n~~~~Thank You~~~~\n");break;
   default:printf("\nINVALID INPUT !!!!\n");
  }
 }while(choice!=4);
}

void enqueue()
{
 if(MAX > count)
 {
  count++;
  struct node * newnode;
  newnode=(struct node *)malloc(sizeof(struct node));
  printf("\nEnter ELEMENT and its PRIORITY respectively\n");
  scanf("%d%d",&newnode->data,&newnode->priority);
  if(head==NULL)
  {
   newnode->next=NULL;
   head=newnode;
  }
  else
  {
   newnode->next=head;
   head=newnode;
  }
 }
 else printf("\nQueue Overflow !!!!!\n");

 
}

void dequeue()
{
 if(count!=0)
 {
  count--;
  int highest;
  struct node* temp, *del;
  temp=head;
  del=head;
  highest=head->priority;
  if(head->next==NULL)
  {
   head=NULL;
   free(del);
  }
  else
  {
   while(temp!=NULL)
   {
    if(temp->priority<=highest)
    {
     del=temp;
     highest=temp->priority;
    }
    temp=temp->next;
   }
   temp=head;
   while(temp->next!=del && head!=del )
   temp=temp->next;
   
   if(del->next==NULL && head!=del)
   {
    temp->next=NULL;
    free(del);
   }
   else if(head==del)
   {
    head=head->next;
    free(del); 
   } 
   else
   {
    temp->next=del->next;
    free(del);
   }
  } 
 }
 else printf("\nQueue Underflow !!!!!\n");

}




void display()
{
 struct node *temp;
 temp=head;
 if(head==NULL)
 printf("\nList is empty...\n");
 else
 {
  printf("List elements are :\t");
  while(temp->next!=NULL)
  {
   printf("%d\t",temp->data);
   temp=temp->next;
  }
  printf("%d\t",temp->data);

 }
}


OUTPUT

Sorted List Ouput 1 Sorted List Ouput 2

Labels: