C program for priority queue: Priority Queue is a queue that we can have value with priority with it.
Priority Queue: A queue based on the properties of priority of a task to be processed is referred to as a Priority Queue.

Priority queue example
The figure shows that N jobs are in with some priority in a queue.

priority queue
priority queue

The priority queue follows FIFO (First in first out) behavior.

Priority queue algorithm

  • Declare structure for a priority queue
  • Inserting in queue
    1. Take input value and priority
    2. Check the priority
    3. Add value to the queue
  • Delete from queue
    1. If front == Empty
    Queue is empty
    2. Else delete from the front
  • Display Queue
    1. If front == Empty
    Queue is empty
    2. Else delete from the front

C program for priority queue

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

typedef struct node{

int pri ;

int data;

struct node *next;

}NODE;
NODE *front=NULL;
// Insert in the priority queue
void insert(int data,int pri)
{
NODE *temp,*q;
temp=(NODE *)malloc (sizeof(NODE));
temp->data=data;
temp->pri=pri;

//check if queue is empty else not check priority of data.

if(front==NULL || pri < front->pri)
{
temp->next =front;
front = temp;
}
else{
q= front;
while(q->next != NULL && q->next->pri <= pri)
q=q->next;
temp->next= q- >next;
q->next =temp;
}}

// Delete in the priority queue.

void del(){
NODE *temp;
if(front == NULL)
printf(“Queue is empty :”);
else
{
temp=front;
printf(“Deleted data is :%d ”,temp->data);
front = front -> next;
free(temp);
}
}
// display the priority queue.

void display(){

NODE *temp;
temp=front;
if(front = = NULL)
printf(“Queue is empty:”);
else
{
printf(“\nOur priority queue is:”);
printf(“Priority Data”\n);
while(temp != NULL)
{
printf(“%5d %5d\n”,temp->pri,ptr->data);
temp->temp->next;
}
}
}

// Start with main function

int main()
{
int ch,data,pri;
do{
printf(“1.Insert\n”);
printf(“2.Delete\n”);
printf(“3.Display\n”);
printf(“4.Exit\n”);
printf(“Enter choice\n”);
scanf(“%d \n”,&ch);
switch(ch)
{
case 1:
printf(“Enter the data:\n”);
scanf(“%d,&data);
printf(“Enter priority:”);
scanf(“%d”,&pri);
insert(data,pri);

break;

case 2:

del();

break;

case 3:

display();

break;

case 4:

break;

default:

printf(“Wrong choice”);

break;
}
}while(ch!=4);
return 0;
}

Output:

C program for priority queue

Write A Comment