Saturday, August 20, 2011

Priority queue using linked list

//Priority queue using linked list
#include<stdio.h>
#include<conio.h>
struct queue 
{
int data;
int p;
struct queue *next;       
};
main()
{
      struct queue *f;
      void insert(struct queue **q,int item,int pr);
      int delet(struct queue **q);
      int item,i;
      int pr;
      f=NULL;
 while(1)
 {
 printf("\n Do you insert element is queue if Yes press \"1\"  otherwise press \"0\" :");
 scanf("%d",&i);
 if(i==1)
 {
         printf("\nEnter the data: ");
         scanf("%d",&item);
          printf("\nEnter the priority: ");
         scanf("%d",&pr);
         insert(&f,item,pr);
 }
 else
 break;
 }
 while(1)
 {
 printf("\n Do you delete element from queue if Yes press \"1\"  otherwise press \"0\" :");
 scanf("%d",&i);
 if(i==1)
 {
         item=delet(&f);
         if(item==-1000)
          {
                        printf("\nUnderflow");
          break;
          }  
         else            
         printf("\nitem deleted from queue is: %d",item);
                  
 }
 else
 break;
 }
 getch();
 return 0;
}

int delet(struct queue **q)
{
    struct queue *p;
    int item;
    if(*q==NULL)
      return -1000;
    p=*q;
    *q=p->next;
    item=p->data;
    free(p);
    return item;
}

void insert(struct queue **q,int item,int pr)
{
  struct queue *p;
  struct queue *prev;
  struct queue *curr;
  p=(struct queue *)malloc(sizeof(struct queue));
   p->data=item;
   p->p=pr;  
  p->next=NULL;
  printf("\npassed address %d\n",*q);
  if(*q==NULL)
  {
    *q=p;
    return;            
  } 
  
  if((p->p)<(*q)->p)
  {
     p->next=*q;
     *q=p; 
     return;
  }
  
  prev=*q;
  curr=(*q)->next;
  while(curr!=NULL)
  {
   if((p->p)<(curr->p))
   {
     p->next=prev->next;
     prev->next=p;  
     return;                  
   }     
   prev=curr;
   curr=curr->next;           
  }
  if(curr==NULL)
  {
   prev->next=p;
  }
}

Previous Next Home
2 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More