Sunday, December 12, 2010

Priority Queue

//program to illustrate Priority Queue Operations
#include
#include

class PriorityQueue
{
struct node
{
int info;
int prio;
node *next;
node *prev;
}*p;

public:
PriorityQueue()
{
p=new node;
p->next=NULL;
p->prev=NULL;
p->prio=-1;
}
void insert(int,int);
void delet(int);
void disp();
};


//inserts a node of given priority
void PriorityQueue::insert(int item,int priority)
{
node *temp,*q;

temp=new node;
temp->info=item;
temp->prio=priority;

//checks the queue is empty
if(p->next==NULL)
{
p->next=temp;
temp->prev=p;
temp->next=NULL;
return;
}

q=p;

while(q->next!=NULL&&q->prio q=q->next;

if(q->prio>priority)
q=q->prev;

temp->next=q->next;
temp->prev=q;
q->next=temp;
(temp->next)->prev=temp;
}


//Deletes an item from the queue
void PriorityQueue::delet(int item)
{
node *q;

if(p->next==NULL)
{
cout<<"\nThe Queue is Empty\n";
return;
}

for(q=p->next;q!=NULL;q=q->next)
{
if(q->info==item)
{
(q->prev)->next=q->next;
(q->next)->prev=q->prev;
cout<<"\nItem Deleted:"<info< cout<<"Priority:"<prio< delete q;
return;
}
}
cout<<"Item not found\n";

}


//displays the node and its contents
void PriorityQueue::disp()
{
node *q;

if(p->next==NULL)
{
cout<<"\nThe Queue is Empty\n";
return;
}

cout<<"\nQUEUE\n-------\n";
for(q=p->next;q!=NULL;q=q->next)
cout<<"Info:"<info<<" Prio:"<prio<
}



void main()
{
PriorityQueue PQ;
int item,prio,ch;
char opt;
int done=1;
clrscr();
cout<<"\n\tPRIORITY QUEUE \n\t---------------\n";
while(done)
{
cout<<"\n\n\tOPERATIONS\n\t-----------\n";
cout<<"\n\t1.INSERT\n\t2.DELETE\n\t3.DISPLAY\n\t4.EXIT\n";
cout<<"\nEnter your option:";
cin>>ch;
switch(ch)
{
case 1: opt='y';
while(opt=='y')
{
cout<<"\nEnter the information:";
cin>>item;
cout<<"\nEnter the priority:";
cin>>prio;
PQ.insert(item,prio);
cout<<"\n\nDo you want to continue?(y/n):";
cin>>opt;
}
break;

case 2: opt='y';
while(opt=='y')
{
cout<<"\nEnter the item:";
cin>>item;
PQ.delet(item);
cout<<"\n\nDo you want to continue?(y/n):";
cin>>opt;
}
break;
case 3: opt='y';
PQ.disp();
break;
case 4: done=0;
break;
default: break;
}
} //end of while...
getch();
}

No comments:

Post a Comment