Priority Queue Implementation in C


#include<stdio.h>

typedef struct queue
{
   int data;
   int priority;
   struct queue *next;
} queue;

queue *front;
queue *rear;

void init()
{
   front = NULL;
   rear = NULL;
}

void enqueue(int x,int priority)
{
   queue *new;
   new = (queue*)malloc(sizeof(queue));
   new->data = x;
   new->priority = priority;
   new->next = NULL;

   if(front == NULL)
   {
     front = new;
     rear = new;
   }
   else
   {
     if(priority > front->priority)
     {
       new->next = front;
       front = new;
     }
    else
    {
      queue *temp;
      temp = front;
      while((temp->next != NULL)&&
          (temp->next->priority > priority))
      {
         temp = temp->next;
      }
      if(temp->next == NULL)
      {
        printf("test 1\n\n");
        new->next = NULL;
        temp->next = new;
        rear = new;
      }
      else
      {
        printf("test 2\n\n");
        new->next = temp->next;
        temp->next = new;
      }

     }
   }
}

int dequeue()
{    
   queue *temp;
   temp = front;
   int x = temp->data;
   front = front->next;
   free(temp);
   return x;
}

void display()
{
   queue *temp;
   temp=front;
   while(temp!=NULL)
   {
      printf("element = %d,priority =%d\n\n",
             temp->data,temp->priority);
      temp = temp->next;
   }
}

int main()
{
    init();
    int total = 0;
    printf("enter the total\n\n");
    scanf("%d",&total);
    int i=0;
    int element = 0,priority=0;
    for(i=0;i<total;i++)
    {
       printf("Enter the element : \t\t");
       scanf("%d",&element);
       printf("Enter the priority : \t\t");
       scanf("%d",&priority);
       enqueue(element,priority);
    }

    printf("queue data\n\n");
    display();

    element = dequeue();
    printf("queue data\n\n");
    display();

    element = dequeue();
    printf("queue data\n\n");
    display();

    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: