-
Notifications
You must be signed in to change notification settings - Fork 1
/
Queue2.c
86 lines (78 loc) · 1.97 KB
/
Queue2.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "priorityqueue_declarations.h"
#include "queue_declarations.h"
struct Node {
unsigned char character;
int visited;
int frequency;
Node *nextNode;
Node *leftNode;
Node *rightNode;
};
struct pqueue {
Node *first;
};
void freePriorityQueue(PriorityQueue* pq){
Node *current;
while(pq->first != NULL){
current = pq->first;
pq->first = pq->first->nextNode;
free(current);
}
}
void printPriorityQueue(PriorityQueue* pq){
Node *current = pq->first;
while(current != NULL){
if(current->character == '\n'){
printf("\\n | %d\n", current->frequency);
} else {
printf("%c | %d\n", current->character, current->frequency);
}
current = current->nextNode;
}
}
PriorityQueue* enqueue(PriorityQueue *pq, unsigned char character, int frequency) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->character = character;
newNode->frequency = frequency;
Node *current = pq->first;
while ((current->nextNode != NULL) && (current->nextNode->frequency < frequency)) {
current = current->nextNode;
}
newNode->nextNode = current->nextNode;
current->nextNode = newNode;
return pq;
}
int QueueisEmpty(PriorityQueue *pq){
return (pq->first == NULL);
}
PriorityQueue* createPriorityQueue(){
PriorityQueue* pq = (PriorityQueue*)malloc(sizeof(PriorityQueue));
pq->first = NULL;
return pq;
}
int queueLength(PriorityQueue *pq){
Node *current = pq->first;
int counter = 0;
while(current != NULL){
current = current->nextNode;
counter++;
}
return counter;
}
Node* dequeue(PriorityQueue *pq) {
if (!QueueisEmpty(pq)){
Node *current = pq->first;
Node *dequeued = (Node*) malloc(sizeof(Node));
memcpy(dequeued, current, sizeof(Node));
pq->first = pq->first->nextNode;
free(current);
return dequeued;
}
else {
printf("Empty priority queue!");
return NULL;
}
}