This repository has been archived by the owner on Aug 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
priorityqueue.c
114 lines (94 loc) · 2.16 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
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
103
104
105
106
107
108
109
110
111
112
113
114
/* TODO: Completely remake! Should use sort on insertion for O(1) peeks, and O(log n) pops (moving pointers is cheap). */
#include <assert.h>
#include <stdlib.h>
#include "priorityqueue.h"
int
prqueuecreate(PriorityQueue *queue, int capacity, int growth)
{
assert(queue != NULL);
assert(queue->entries == NULL);
assert(capacity >= 0 && growth >= 0);
assert(capacity > 0 || growth > 0);
queue->entries = malloc(sizeof(*queue->entries) * capacity);
if (queue->entries) {
queue->capacity = capacity;
queue->growth = growth;
queue->count = 0;
return 1;
} else {
queue->capacity = 0;
queue->growth = 0;
queue->count = 0;
return 0;
}
}
void
prqueuedestroy(PriorityQueue *queue)
{
assert(queue != NULL);
assert(queue->entries != NULL);
queue->capacity = 0;
queue->growth = 0;
queue->count = 0;
free(queue->entries);
queue->entries = NULL;
}
int
prqueuegrow(PriorityQueue *queue)
{
//
}
void*
prqueuepeek(PriorityQueue *queue)
{
assert(queue != NULL);
assert(queue->entries != NULL);
if (queue->count > 0) {
int i;
int toppriority;
void *topentry;
toppriority = queue->entries[0]->priority;
topentry = queue->entries[0]->value;
for (i = 1; i < queue->count; i++) {
if (queue->entries[i]->priority > toppriority) {
toppriority = queue->entries[i]->priority;
topentry = queue->entries[i]->value;
}
}
return topentry;
}
return NULL;
}
void*
prqueuepop(PriorityQueue *queue)
{
assert(queue != NULL);
assert(queue->entries != NULL);
if (queue->count > 0) {
int i;
int topindex;
int toppriority;
void *topentry;
topindex = 0;
toppriority = queue->entries[0]->priority;
topentry = queue->entries[0]->value;
for (i = 1; i < queue->count; i++) {
if (queue->entries[i]->priority > toppriority) {
topindex = i;
toppriority = queue->entries[i]->priority;
topentry = queue->entries[i]->value;
}
}
for (i = toppriority; i < queue->count - 1; i++)
queue->entries[i] = queue->entries[i + 1];
queue->entries[queue->count] = NULL;
queue->count--;
return topentry;
}
return NULL;
}
int
prqueuepush(PriorityQueue *queue, int priority, void *value)
{
// Remember, need to allocate a new PriorityValue
}