-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathPriority_Queue_using_doubly_linked_list.cpp
84 lines (73 loc) · 1.45 KB
/
Priority_Queue_using_doubly_linked_list.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
// CPP code to implement priority queue using doubly linked list
#include <bits/stdc++.h>
using namespace std;
struct Node {
int info;
int priority;
struct Node *prev, *next;
};
void push(Node** fr, Node** rr, int n, int p)
{
Node* news = (Node*)malloc(sizeof(Node));
news->info = n;
news->priority = p;
if (*fr == NULL) {
*fr = news;
*rr = news;
news->next = NULL;
}
else {
if (p <= (*fr)->priority) {
news->next = *fr;
(*fr)->prev = news->next;
*fr = news;
}
else if (p > (*rr)->priority) {
news->next = NULL;
(*rr)->next = news;
news->prev = (*rr)->next;
*rr = news;
}
else {
Node* start = (*fr)->next;
while (start->priority > p)
start = start->next;
(start->prev)->next = news;
news->next = start->prev;
news->prev = (start->prev)->next;
start->prev = news->next;
}
}
}
int peek(Node *fr)
{
return fr->info;
}
bool isEmpty(Node *fr)
{
return (fr == NULL);
}
int pop(Node** fr, Node** rr)
{
Node* temp = *fr;
int res = temp->info;
(*fr) = (*fr)->next;
free(temp);
if (*fr == NULL)
*rr = NULL;
return res;
}
// Driver code :
int main()
{
Node *front = NULL, *rear = NULL;
push(&front, &rear, 2, 3);
push(&front, &rear, 3, 4);
push(&front, &rear, 4, 5);
push(&front, &rear, 5, 6);
push(&front, &rear, 6, 7);
push(&front, &rear, 1, 2);
cout << pop(&front, &rear) << endl;
cout << peek(front);
return 0;
}