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 | // Copyright 2021 Jeisson Hidalgo-Cespedes <jeisson.hidalgo@ucr.ac.cr> CC-BY-4
#include <assert.h>
#include <stdlib.h>
#include "queue.h"
void queue_remove_first(queue_t* queue);
int queue_init(queue_t* queue) {
assert(queue);
queue->head = NULL;
queue->tail = NULL;
return EXIT_SUCCESS;
}
int queue_destroy(queue_t* queue) {
queue_clear(queue);
return EXIT_SUCCESS;
}
bool queue_is_empty(queue_t* queue) {
assert(queue);
return queue->head == NULL;
}
int queue_enqueue(queue_t* queue, const size_t data) {
assert(queue);
int error = EXIT_SUCCESS;
queue_node_t* new_node = (queue_node_t*) calloc(1, sizeof(queue_node_t));
if (new_node) {
new_node->data = data;
if (queue->tail) {
queue->tail = queue->tail->next = new_node;
} else {
queue->head = queue->tail = new_node;
}
} else {
error = EXIT_FAILURE;
}
return error;
}
int queue_dequeue(queue_t* queue, size_t* data) {
assert(queue);
int error = 0;
if (!queue_is_empty(queue)) {
if (data) {
*data = queue->head->data;
}
queue_remove_first(queue);
} else {
error = EXIT_FAILURE;
}
return error;
}
void queue_remove_first(queue_t* queue) {
assert(queue);
assert(!queue_is_empty(queue));
queue_node_t* node = queue->head;
queue->head = queue->head->next;
free(node);
if (queue->head == NULL) {
queue->tail = NULL;
}
}
void queue_clear(queue_t* queue) {
assert(queue);
while (!queue_is_empty(queue)) {
queue_remove_first(queue);
}
}
|