-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriority_queue.c
More file actions
50 lines (41 loc) · 896 Bytes
/
priority_queue.c
File metadata and controls
50 lines (41 loc) · 896 Bytes
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
#include <stdlib.h>
#include "priority_queue.h"
Node *enqueue(Node **pq, void *value, int (*cmpFunc)(const void*, const void*))
{
Node *node = calloc(1, sizeof(*node));
node -> value = value;
node -> next = NULL;
if (*pq == NULL || cmpFunc(node -> value, (*pq) -> value) < 0) {
node -> next = *pq;
*pq = node;
} else {
Node *curr, *prev;
prev = curr = *pq;
while (curr != NULL && cmpFunc(node -> value, curr -> value) >= 0) {
prev = curr;
curr = curr -> next;
}
prev -> next = node;
node -> next = curr;
}
return node;
}
Node *dequeue(Node **pq)
{
Node *node = *pq;
if (node != NULL) {
*pq = (*pq) -> next;
node -> next = NULL;
}
return node;
}
void destroyList(Node **head, void (*destroyFunc)(void*))
{
while (*head != NULL) {
Node *node = (*head) -> next;
destroyFunc((*head) -> value);
free(*head);
*head = node;
}
*head = NULL;
}