-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpq.c
More file actions
100 lines (74 loc) · 1.89 KB
/
pq.c
File metadata and controls
100 lines (74 loc) · 1.89 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
#include "pq.h"
#include <stdbool.h>
#include <stdio.h>
/* put in pq.c */
typedef struct ListElement ListElement;
struct ListElement {
Node *tree;
ListElement *next;
};
struct PriorityQueue {
ListElement *list;
};
bool pq_less_than(Node *n1, Node *n2) {
if (n1->weight < n2->weight)
return true;
if (n1->weight > n2->weight)
return false;
return n1->symbol < n2->symbol;
}
PriorityQueue *pq_create(void) {
PriorityQueue *pq = calloc(1, sizeof(PriorityQueue));
return pq;
}
void pq_free(PriorityQueue **q) {
free(*q);
*q = NULL;
}
bool pq_is_empty(PriorityQueue *q) {
return q->list == NULL;
}
bool pq_size_is_1(PriorityQueue *q) {
return !(pq_is_empty(q)) && q->list->next == NULL;
}
void enqueue(PriorityQueue *q, Node *tree) {
ListElement *e = calloc(1, sizeof(ListElement));
e->tree = tree;
if (pq_is_empty(q)) {
q->list = e;
} else if (pq_less_than(e->tree, q->list->tree)) {
e->next = q->list;
q->list = e;
} else {
ListElement *li = q->list;
while (li->next != NULL && !pq_less_than(tree, li->next->tree)) {
li = li->next;
}
e->next = li->next;
li->next = e;
}
}
bool dequeue(PriorityQueue *q, Node **tree) {
if (pq_is_empty(q))
return NULL;
ListElement *head = q->list;
q->list = head->next;
*tree = head->tree;
free(head);
return true;
}
void pq_print(PriorityQueue *q) {
assert(q != NULL);
ListElement *e = q->list;
int position = 1;
while (e != NULL) {
if (position++ == 1) {
printf("=============================================\n");
} else {
printf("---------------------------------------------\n");
}
node_print_tree(e->tree, '<', 2);
e = e->next;
}
printf("=============================================\n");
}