blob: 6a472ee9bc1bb24727d2c2188bf93847722a2207 (
plain)
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
115
|
/* Standard C */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
/* Project */
#include "util.h"
/* --8<-- queue_type */
typedef int T;
struct queue_item {
struct queue_item *next;
T data;
};
struct queue {
struct queue_item *head, *tail;
};
/* -->8-- */
/* --8<-- queue_init */
void
queue_init(struct queue *queue)
{
queue->head = NULL;
}
/* -->8-- */
/* --8<-- queue_put */
void
queue_put(struct queue *queue, T data)
{
struct queue_item *new_item;
if ( (new_item = malloc(sizeof *new_item)) != NULL ) {
struct queue_item *tmp = queue->tail;
new_item->data = data;
new_item->next = NULL;
queue->tail = new_item;
if ( queue->head == NULL )
queue->head = queue->tail;
else
tmp->next = queue->tail;
}
else {
ERROR("out of memory");
}
}
/* -->8-- */
/* --8<-- queue_get */
bool
queue_get(struct queue *queue, T *data)
{
if ( queue->head ) {
struct queue_item *next = queue->head->next;
if ( data ) {
*data = queue->head->data;
}
free(queue->head);
queue->head = next;
return true;
}
else
return false;
}
/* -->8-- */
/* --8<-- queue_empty */
bool
queue_empty(struct queue *queue)
{
return queue->head == NULL;
}
/* -->8-- */
/* --8<-- queue_free */
void
queue_free(struct queue *queue)
{
struct queue_item *item, *next;
for ( item = queue->head; item; item = next ) {
next = item->next;
free(item);
}
}
/* -->8-- */
int
main()
{
struct queue queue[1];
queue_init(queue);
for ( int i = 0; i != 10; ++i ) {
queue_put(queue, i);
}
while ( !queue_empty(queue) ) {
int i;
if ( queue_get(queue, &i) )
printf("%d\n", i);
else
ERROR("this shouldn't happen!");
}
queue_free(queue);
return EXIT_SUCCESS;
}
|