In: Computer Science
C++
Program 1–Implement a Priority Queue(PQ) using an UNSORTED LIST. Use an array size of 10 elements. Use a circular array: Next index after last index is 0. Add the new node to next available index in the array. When you add an element, add 1 to index (hit max index, go to index 0). Test if array in full before you add. When you remove an element, from the list, move the following elements to the left to fill in the blank, etc ( Like prior program done with LISTS )
Solution:
PROGRAM 1:
CODE:
#include <iostream>
using namespace std;
const int MAX=10;
/*Create struct node with maximum limit value*/
struct node
{
int data;
string nameVal;
int priorityVal;
}d[MAX];
/*Class for priority queue with attributes of name and
priority*/
class pqueue
{
int front,rear;
public:
pqueue()
{
front=rear=-1;
}
void enqueue(struct node d1);
struct node dequeue();
void display();
};
/*Enqueue - insert/add the value to the queue*/
void pqueue :: enqueue(struct node d1)
{
if(rear==MAX-1) //-- check queue is full or not before adding value
to queue
cout<<"Priority Queue is Full";
else
{
rear++;
d[rear]=d1;
if(front==-1)
front=0;
struct node temp;
for(int i=front;i<=rear;i++)
for(int j=i+1;j<=rear;j++)
{
if(d[i].priorityVal > d[j].priorityVal) //-- insert values based
on it's priority order
{
temp=d[i];
d[i]=d[j];
d[j]=temp;
}
else
{
if(d[i].priorityVal==d[j].priorityVal)
{
temp=d[i];
d[i]=d[j];
d[j]=temp;
}
}
}
}
}
struct node pqueue :: dequeue()
{
struct node d1;
if(front==-1) //-- check queue is empty before deleting elements
from it.
cout<<"Priority Queue is Empty";
else
{
d1=d[front];
if(front==rear)
front=rear=-1;
else
front++;
}
return d1;
}
/*Display the list of elements in the queue*/
void pqueue :: display()
{
if(front==-1)
cout<<"Priority Queue is Empty";
else
{
for(int i=front;i<=rear;i++)
{
cout<<"Name ="<<d[i].nameVal<<endl;
cout<<"Priority="<<d[i].priorityVal<<endl;
}
}
}
int main()
{
pqueue p1;
struct node d1;
char op;
do
{
int ch;
cout<<"1.Enqueue " << endl << "2.Dequeue"
<< endl << "3.Display" << endl << "4.Exit"
<< endl;
cout<<"Enter your Choice(1..4) ?";
cin>>ch;
switch(ch)
{
case 1 : cout<<"Enter Name ?"<<endl;
cin>>d1.nameVal;
cout<<"Enter Priority?"<<endl;
cin>>d1.priorityVal;
p1.enqueue(d1);
break;
case 2 : d1=p1.dequeue();
cout << "Dequeued data"<<endl;
cout<<"Name = "<<d1.nameVal<<endl;
cout<<"Priority = "<<d1.priorityVal<<endl;
break;
case 3 : p1.display();
break;
}
cout<<"Do You Want to Continue <Y/N> ?";
cin>>op;
}while(op=='Y' || op=='y');
}
Sample output:
#please consider my effort and give me a like..thank u...