-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriorityqueuelinked.c
More file actions
60 lines (53 loc) · 1.46 KB
/
priorityqueuelinked.c
File metadata and controls
60 lines (53 loc) · 1.46 KB
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
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *front = NULL;
// In this implementation, the higher value = higher priority.
// It inserts items in descending sorted order.
void enqueuePriority(int value) {
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = value;
// If list is empty or new node has highest priority, put it at front
if (front == NULL || value > front->data) {
newNode->next = front;
front = newNode;
return;
}
// Otherwise, traverse to find its proper sorted spot
struct node *temp = front;
while (temp->next != NULL && temp->next->data >= value) {
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
void dequeue() {
if (front == NULL) {
printf("Priority Queue is Empty\n");
return;
}
struct node *temp = front;
printf("Processed highest priority item: %d\n", front->data);
front = front->next;
free(temp);
}
void display() {
struct node *temp = front;
if (temp == NULL) { printf("Priority Queue is Empty\n"); return; }
printf("Priority Queue: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
enqueuePriority(10); enqueuePriority(30); enqueuePriority(20);
display();
dequeue();
display();
return 0;
}