/* C++ program Priority Queue using Template */
#include<iostream>
#include<stdlib.h>
using namespace std;
template <class T>
class PQ
{
struct node
{
T data;
int priority;
struct node *link;
}*head;
public: void insert(T,int);
void delet();
void display();
};
template <class T>
void PQ<T> :: insert(T item,int prio)
{
struct node *p,*temp;
temp=new node;
temp->data=item;
temp->priority=prio;
if(head==NULL || prio<head->priority)
{
temp->link=head;
head=temp;
}
else
{
p=head;
while(p->link!=NULL && p->link->priority<=prio)
p=p->link;
temp->link=p->link;
p->link=temp;
}
}
template <class T>
void PQ<T> :: delet()
{
if(head==NULL)
cout<<"Queue underflow";
else
{
struct node *temp;
cout<<"\nDeleted item is "<<head->data;
temp=head;
head=head->link;
free(temp);
}
}
template <class T>
void PQ<T> :: display()
{
if(head==NULL)
cout<<"Queue underflow";
else
{
cout<<"\nPriority Queue is\n";
struct node *temp;
for(temp=head;temp!=NULL;temp=temp->link)
cout<<"\t"<<temp->data;
}
}
int main()
{
PQ <int>p;
while(1)
{
cout<<"\n1.Insert\n2.Delete\n3.Display\n4.Exit";
cout<<"\nEnter choice: ";
int ch;
cin>>ch;
switch(ch)
{
case 1: int item,prio;
cout<<"\nEnter data to insert: ";
cin>>item;
cout<<"\nEnter Priority of "<<item<<": ";
cin>>prio;
p.insert(item,prio);
break;
case 2: p.delet();
break;
case 3: p.display();
break;
case 4: exit(0);
default: cout<<"\n wrong choice given....";
}
}
return(0);
}
No comments:
Post a Comment