Skip to main content

Implementation of Priority Queue

Implementation of Priority Queue 


CODE
👇
  1. #include<stdio.h>
  2. #define MAX 50
  3. typedef struct
  4. {
  5. int data[MAX];
  6. int front,rear;
  7. }QUEUE;

  8. void InitQ(QUEUE *pq)
  9. {
  10.   pq->front = pq->rear = -1;
  11. }

  12. void AddQ(QUEUE *pq, int num)
  13. {
  14. int i;
  15. for(i=pq->rear;i>pq->front;i--)
  16.     if(num>pq->data[i])
  17.   pq->data[i+1]=pq->data[i];//shift element
  18.         else
  19.         break;
  20.        pq->data[i+1]=num;
  21.        pq->rear++;
  22. }

  23. int DelQ(QUEUE *pq)
  24. {
  25. int num;
  26.   pq->front++;
  27.   num=pq->data[pq->front];
  28.     return(num);
  29. }

  30. int isempty(QUEUE *pq)
  31. {
  32. return(pq->front == pq->rear);
  33. }

  34. int isfull(QUEUE *pq)
  35. {
  36.   return(pq->rear==MAX-1);
  37. }

  38. void main()
  39. {
  40.   int num,choice;
  41.   QUEUE q1;
  42.   InitQ(&q1);
  43.   printf(">>Implementation of Priority Queue<<");
  44.   do
  45.   {
  46.     printf("\n1: Add \n");
  47.     printf("2: Delete \n");
  48.     printf("3: Exit \n");
  49.     printf("Enter Your Choice: \t");
  50.     scanf("%d",&choice);

  51.     switch(choice)
  52.     {
  53.       case 1: printf("Enter Element To Be Added:\t");
  54.       scanf("%d",&num);
  55.       if(isfull(&q1))
  56.       printf("\t>>Queue Overflow<<\n");
  57.       else
  58.       AddQ(&q1,num);
  59.       break;

  60.       case 2: if(isempty(&q1)==1)
  61.       printf("\t>>Queue Is Empty<<\n");
  62.       else
  63.       printf("The Deleted Element Is:\t %d \n",DelQ(&q1));
  64.       break;

  65.       case 3: printf("\t>>END<<");
  66.       break;
  67.      
  68.       default:printf("\t>>Enter Right Choice<<");
  69.     }
  70.   }
  71.  while(choice!=3);
  72. }

👉Excute👈

//Output
/*
>>Implementation of Priority Queue<<
1: Add
2: Delete
3: Exit
Enter Your Choice:      2
        >>Queue Is Empty<<

1: Add
2: Delete
3: Exit
Enter Your Choice:      1
Enter Element To Be Added:      5

1: Add
2: Delete
3: Exit
Enter Your Choice:      2
The Deleted Element Is:  5

1: Add
2: Delete
3: Exit
Enter Your Choice:      4
        >>Enter Right Choice<<
1: Add
2: Delete
3: Exit
Enter Your Choice:      3
        >>END<<
*/


                                                           //ThE ProFessoR

Comments