Introduce old redir program
[lcapit-junk-code.git] / static-data-structures / queue.c
blob35aacc8f3002647f41edc6b55e770ffe4698f2eb
1 #include <stdio.h>
3 #define MAX_QUEUE_SIZE 16
5 struct data {
6 int code;
7 };
9 struct queue {
10 struct data data[MAX_QUEUE_SIZE];
11 int first;
12 int last;
15 static void queue_init(struct queue *queue)
17 queue->first = queue->last = 0;
20 static int queue_empty(const struct queue *queue)
22 return queue->first == queue->last;
25 static int queue_insert(struct queue *queue, struct data *data)
27 if (queue->last == MAX_QUEUE_SIZE)
28 return -1;
30 queue->data[queue->last] = *data;
31 queue->last++;
33 return 0;
36 static int queue_remove(struct queue *queue, struct data *ret)
38 int i;
40 if (queue_empty(queue))
41 return -1;
43 if (ret)
44 *ret = queue->data[queue->first];
46 queue->last--;
47 for (i = queue->first; i < queue->last; i++)
48 queue->data[i] = queue->data[i + 1];
50 return 0;
53 static void queue_print(const struct queue *queue)
55 int i;
57 if (queue_empty(queue))
58 return;
60 for (i = queue->first; i < queue->last; i++)
61 printf("%d ", queue->data[i].code);
62 printf("\n");
65 static void fill_data(struct data *data, int code)
67 data->code = code;
70 int main(void)
72 struct queue queue;
73 struct data data1, data2, data3, data_ret;
75 queue_init(&queue);
77 if (queue_empty(&queue))
78 printf("Queue is empty\n");
79 else
80 printf("Queue is not empty\n");
82 fill_data(&data1, 0);
83 fill_data(&data2, 1);
84 fill_data(&data3, 2);
86 queue_insert(&queue, &data1);
87 queue_insert(&queue, &data2);
88 queue_insert(&queue, &data3);
90 if (queue_empty(&queue))
91 printf("Queue is empty\n");
92 else
93 printf("Queue is not empty\n");
95 queue_print(&queue);
97 queue_remove(&queue, &data_ret);
98 printf("Item removed: %d\n", data_ret.code);
100 queue_print(&queue);
102 return 0;