-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
94 lines (78 loc) · 1.7 KB
/
queue.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
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "queue.h"
QUEUE_PTR create_new_queue() {
QUEUE_PTR p = (QUEUE_PTR)malloc(sizeof(QUEUE));
if (p == NULL) {
printf("Memory allocation for queue failed!\n");
return NULL;
}
p->node_count = 0;
p->tail = NULL;
p->head = NULL;
}
void destroy_queue(QUEUE_PTR q) {
QUEUE_NODE_PTR p = q->head;
while (p != NULL) {
QUEUE_NODE_PTR r = p;
p = p->next;
if (r->data != NULL) {
free(r->data);
}
free(r);
}
free(q);
}
void process_queue(QUEUE_PTR q, bool (*proc)(void *data)) {
QUEUE_NODE_PTR p = q->head;
while (p != NULL) {
if (proc(p->data)) {
break;
}
p = p->next;
}
}
bool enqueue(QUEUE_PTR q, void *data) {
if (q == NULL) {
printf("Queue isn\'t allocated!\n");
return false;
}
QUEUE_NODE_PTR n = (QUEUE_NODE_PTR)malloc(sizeof(QUEUE_NODE));
if (n == NULL) {
printf("Memory allocation for queue_node failed!\n");
return false;
}
n->data = data;
n->next = NULL;
if (q->tail == NULL) {
q->head = q->tail = n;
} else {
q->tail->next = n;
q->tail = n;
}
q->node_count++;
return true;
}
void *dequeue(QUEUE_PTR q) {
if (q->head == NULL) {
return NULL;
}
QUEUE_NODE_PTR p = q->head;
q->node_count--;
if (q->head != q->tail) {
q->head = q->head->next;
} else {
q->head = NULL;
q->tail = NULL;
}
void *data = p->data;
free(p);
return data;
}
int queue_size(QUEUE_PTR q) {
if (q == NULL) {
return 0;
}
return q->node_count;
}