-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpriorityQueue.c
57 lines (46 loc) · 1.66 KB
/
priorityQueue.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
#include <stdio.h> //for printf()
#include <stdlib.h> //for malloc() and NULL
#include "priorityQueue.h"
struct priority_queue;
struct pq_node;
pq_node* findLastElementWithPriorityX(int priority, priority_queue *queue){
pq_node* current = queue->first;
printf("priority: %d, value: %d\n", current->priority, current->value);
if(current == NULL){
printf("Nothing here!\n");
return NULL;
}
while(current->next != NULL && current->next->priority < priority+1){
current = current->next;
printf("priority: %d, value: %d\n", current->priority, current->value);
}
return current;
}
void insertIntoPriorityQueue(int priority, int value, priority_queue *queue){
pq_node* lastNodeWithHigherPriority = findLastElementWithPriorityX(priority, queue);
pq_node *newNode = malloc(sizeof(pq_node));
*newNode = (pq_node){priority, value, NULL};
if(lastNodeWithHigherPriority == NULL){
queue->first = newNode;
}
else {
pq_node* firstElementWithLowerPriority = lastNodeWithHigherPriority->next;
newNode->next = firstElementWithLowerPriority;
lastNodeWithHigherPriority->next = newNode;
}
}
void traversePriorityQueue(priority_queue *queue){
pq_node* current = queue->first;
printf("\n\npriority: %d, value: %d\n", current->priority, current->value);
while(current->next !=NULL){
current = current->next;
printf("priority: %d, value: %d\n", current->priority, current->value);
}
}
int popPriorityQueue(priority_queue *queue){
int poppedValue = queue->first->value;
pq_node* newHead = queue->first->next;
free(queue->first);
queue->first = newHead;
return poppedValue;
}