-
Notifications
You must be signed in to change notification settings - Fork 0
/
46john20.c
83 lines (71 loc) · 1.79 KB
/
46john20.c
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
/*
Roll no:46
Batch:B
Author Name:John Joy
Date:2/10/23
Description:Linked list implementation of priority queue
*/
#include <stdio.h>
#include <stdlib.h>
struct node {
int info;
int pr;
struct node *next;
};
struct node *list = NULL;// start of linked list
// Function to allocate memory to a new node
struct node* getnode(void) {
return (struct node*)malloc(sizeof(struct node));
}
// Function to free memory of node
void freenode(struct node *p) {
free(p);
}
// Enqueue an element with its priority
void enqueue(int x, int pr) {
struct node *temp, *nn;
nn = getnode();
nn->info = x;
nn->pr = pr;
nn->next = NULL;
if (list == NULL || pr < list->pr) {
nn->next = list;
list = nn;
} else {
temp = list;
while (temp->next != NULL && nn->pr > temp->pr) {
temp = temp->next;
}
nn->next = temp->next;
temp->next = nn;
}
}
// Dequeue the element with the highest priority
int dequeue() {
if (list == NULL) {
printf("Queue is empty\n");
return -1; // indicating an empty queue
}
struct node *temp = list;
int data = temp->info;
list = list->next;
freenode(temp);
return data;
}
int main() {
int num_elements;
printf("Enter the number of elements: ");
scanf("%d", &num_elements);
for (int i = 0; i < num_elements; i++) {
int data, priority;
printf("Enter element %d and its priority: ", i + 1);
scanf("%d %d", &data, &priority);
enqueue(data, priority);
}
printf("\nDequeueing elements in priority order:\n");
while (list != NULL) {
int data = dequeue();
printf("Dequeued: %d\n", data);
}
return 0;
}