forked from doctor-phil/network
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriority_queue.cpp
More file actions
102 lines (78 loc) · 2.08 KB
/
Copy pathpriority_queue.cpp
File metadata and controls
102 lines (78 loc) · 2.08 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* This priority_queue.c file implements the functions declared in the priority_queue.h file.
* Note: a compare function pointer must be passed to the pQueue_initialize function
* to have the priority queue function properly. Otherwise, undefined behavior could occur.
*
* Below is an example compare function that can be passed into the PriorityQueue struct
* that is then used in _pQueue_sort to sort the PriorityQueue accordingly.
*
* int compareFunction(void* a, void* b)
* {
return (*(int*)a - *(int*)b);
* }
*/
#include "priority_queue.h"
#include "linked_list.h"
#include <stdio.h>
PriorityQueue* pQueue_initialize(int itemSize, char* typeName, int (*compareFunction)(void*,void*))
{
PriorityQueue* pq = (PriorityQueue*)malloc(sizeof(*pq));
if(pq == NULL)
return NULL;
pq->list = linked_list_initialize(itemSize, typeName);
pq->compare = compareFunction;
return pq;
}
bool pQueue_enqueue(PriorityQueue* pq, void* element)
{
if(pq == NULL || element == NULL)
return false;
bool result = linked_list_add_first(pq->list, element);
_pQueue_sort(pq);
return result;
}
void* pQueue_dequeue(PriorityQueue* pq)
{
if(pq == NULL)
return NULL;
return linked_list_remove_last(pq->list);
}
void* pQueue_peek(PriorityQueue* pq)
{
if(pq == NULL)
return NULL;
int end = linked_list_size(pq->list) - 1;
return linked_list_get(pq->list, end);
}
int pQueue_size(PriorityQueue* pq)
{
if(pq == NULL)
return -1;
return linked_list_size(pq->list);
}
bool pQueue_contains(PriorityQueue* pq, void* element)
{
if(pq == NULL || element == NULL)
return false;
return -1 != linked_list_index_of(pq->list, element);
}
void _pQueue_sort(PriorityQueue* pq)
{
if(pq == NULL)
return;
int size = linked_list_size(pq->list);
for(int i = 0; i < size; i++)
{
void* outer = linked_list_get(pq->list, i);
for(int j = i + 1; j < size; j++)
{
void* inner = linked_list_get(pq->list, j);
int directional = pq->compare(outer, inner);
if(directional < 0)
{
// call linked_list_swap(int i, int j) here
linked_list_swap(pq->list, i, j);
}
}
}
}