Implement a heap-based priority queue CLASS containing characters using a zero-b
ID: 3729548 • Letter: I
Question
Implement a heap-based priority queue CLASS containing characters using a zero-based array of these records. You may assume that the heap will contain no more than 255 elements. Implement two functions “insert” and “remove”. Function “insert” takes a character as an input and insert it to the priority queue. Function “remove” removes a character with the highest priority, that is to remove the minimum (alphabetically first) character from the queue. Provide the class in C++. Also, write a simple separate program that uses the heap-based queue class.
Explanation / Answer
C++ Program to Implement Priority Queue
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
/*
* Node Declaration
*/
struct node
{
int priority;
int info;
struct node *link;
};
/*
* Class Priority Queue
*/
class Priority_Queue
{
private:
node *front;
public:
Priority_Queue()
{
front = NULL;
}
/*
* Insert into Priority Queue
*/
void insert(int item, int priority)
{
node *tmp, *q;
tmp = new node;
tmp->info = item;
tmp->priority = priority;
if (front == NULL || priority < front->priority)
{
tmp->link = front;
front = tmp;
}
else
{
q = front;
while (q->link != NULL && q->link->priority <= priority)
q=q->link;
tmp->link = q->link;
q->link = tmp;
}
}
/*
* Delete from Priority Queue
*/
void del()
{
node *tmp;
if(front == NULL)
cout<<"Queue Underflow ";
else
{
tmp = front;
cout<<"Deleted item is: "<<tmp->info<<endl;
front = front->link;
free(tmp);
}
}
/*
* Print Priority Queue
*/
void display()
{
node *ptr;
ptr = front;
if (front == NULL)
cout<<"Queue is empty ";
else
{ cout<<"Queue is : ";
cout<<"Priority Item ";
while(ptr != NULL)
{
cout<<ptr->priority<<" "<<ptr->info<<endl;
ptr = ptr->link;
}
}
}
};
/*
* Main
*/
int main()
{
int choice, item, priority;
Priority_Queue pq;
do
{
cout<<"1.Insert ";
cout<<"2.Delete ";
cout<<"3.Display ";
cout<<"4.Quit ";
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Input the item value to be added in the queue : ";
cin>>item;
cout<<"Enter its priority : ";
cin>>priority;
pq.insert(item, priority);
break;
case 2:
pq.del();
break;
case 3:
pq.display();
break;
case 4:
break;
default :
cout<<"Wrong choice ";
}
}
while(choice != 4);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.