-
Notifications
You must be signed in to change notification settings - Fork 1
/
MaxPriorityQueue_By_LL.cpp
101 lines (85 loc) · 2.04 KB
/
MaxPriorityQueue_By_LL.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<iostream>
using namespace std;
// Max-Priority Queue using linked list
class Node{
public:
int data;
int priority;
Node* next;
Node(int val,int prior): data(val) , priority(prior) , next(nullptr){};
};
class PriorityQueue{
Node* front;
Node* rear;
int size;
public:
PriorityQueue(){
size = 0;
front = rear = NULL;
}
void insert(int,int);
int poll(); // dequeue
bool isempty();
int getSize(){
return size;
}
};
bool PriorityQueue :: isempty(){
return (!front || !rear);
}
void PriorityQueue :: insert(int val , int priority){
size++;
Node* newnode = new Node(val,priority);
// Insert at beginning if queue is empty or element has highest priority than front ka element
if(!front){
newnode->next = front;
front = rear = newnode;
}
else if((priority > front->priority)){
newnode->next = front;
front = newnode;
}
else if( priority < rear->priority ){
// Insert at end
rear->next = newnode;
rear = newnode;
}
else{
// Find suitable place to insert
Node* temp = front;
while (temp->next && (temp->next->priority > priority)) {
temp = temp->next;
}
newnode->next = temp->next;
temp->next = newnode;
}
}
int PriorityQueue :: poll(){
if(!isempty()){
int first = front->data;
front = front->next;
size--;
return first;
}
return -1;
}
void display(PriorityQueue pq){
while(!pq.isempty()){
cout << pq.poll() << " " ;
}
cout << endl ;
}
int main(){
PriorityQueue pq;
for(int i=1;i<=5;i++){
int data,prior;
cout << "Enter data and priority : ";
cin >> data >> prior;
pq.insert(data,prior);
}
display(pq);
cout <<"\nFront element is : " <<pq.poll() << endl;
display(pq);
cout <<"Queue size is : "<< pq.getSize() << endl;
return 0;
}