aboutsummaryrefslogtreecommitdiff
path: root/deque.c
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2020-07-22 17:30:45 +0200
committerThomas Schmucker <ts@its1.de>2020-07-22 17:30:45 +0200
commitac55496d881e0a17b3eff85f1faae5aafbc53b50 (patch)
tree65b954e994d7bbfc76bc959876e28f7ea9fa708c /deque.c
downloaddata-structures-ac55496d881e0a17b3eff85f1faae5aafbc53b50.tar.gz
data-structures-ac55496d881e0a17b3eff85f1faae5aafbc53b50.tar.bz2
data-structures-ac55496d881e0a17b3eff85f1faae5aafbc53b50.zip
erster Commit
Diffstat (limited to 'deque.c')
-rw-r--r--deque.c125
1 files changed, 125 insertions, 0 deletions
diff --git a/deque.c b/deque.c
new file mode 100644
index 0000000..7125764
--- /dev/null
+++ b/deque.c
@@ -0,0 +1,125 @@
1#include <stdio.h>
2#include <stdlib.h>
3#include <stdbool.h>
4
5#define NELEM(x) (sizeof(x) / sizeof(x[0]))
6
7typedef int T;
8
9struct chunk {
10 int head, tail;
11 T array[8];
12};
13
14static void
15chunk_init(struct chunk *c)
16{
17 c->head = 0;
18 c->tail = 0;
19}
20
21static bool
22chunk_put(struct chunk *c, T data)
23{
24 const int next = (c->head + 1) % NELEM(c->array);
25
26 if ( next == c->tail ) /* full? */
27 return false;
28
29 c->array[c->head] = data;
30 c->head = next;
31
32 return true;
33}
34
35static bool
36chunk_get(struct chunk *c, T *data)
37{
38 if ( c->head == c->tail ) /* empty? */
39 return false;
40
41 const int next = (c->tail + 1) % NELEM(c->array);
42
43 *data = c->array[c->tail];
44 c->tail = next;
45
46 return true;
47}
48
49static int
50chunk_size(struct chunk *c)
51{
52 return (c->head + NELEM(c->array) - c->tail) % NELEM(c->array);
53}
54
55static bool
56chunk_full(struct chunk *c)
57{
58 return ((c->head + 1) % NELEM(c->array)) == c->tail;
59}
60
61static bool
62chunk_empty(struct chunk *c)
63{
64 return c->head == c->tail;
65}
66
67static T*
68chunk_at(struct chunk *c, int idx)
69{
70 if ( idx < 0 || idx >= chunk_size(c) ) /* invalid index? */
71 return NULL;
72
73 return &c->array[(c->head + idx) % NELEM(c->array)];
74}
75
76/* ================= */
77
78struct deque {
79 int head, tail, capacity;
80
81 struct chunk **chunks;
82};
83
84void
85deque_init(struct deque *d)
86{
87 int i;
88
89 d->head = 0;
90 d->tail = 0;
91 d->capacity = 1;
92
93 d->chunks = calloc(d->capacity, sizeof(struct chunk *));
94
95 for ( i = 0; i != d->capacity; ++i ) {
96 d->chunks[i] = malloc(sizeof(struct chunk));
97 chunk_init(d->chunks[i]);
98 }
99}
100
101
102int main(void)
103{
104 struct chunk c;
105 int data;
106
107 chunk_init(&c);
108
109 chunk_put(&c, '0');
110 chunk_put(&c, '0');
111 chunk_get(&c, &data);
112 chunk_get(&c, &data);
113
114 chunk_put(&c, 'A');
115 chunk_put(&c, 'B');
116 chunk_put(&c, 'C');
117 chunk_put(&c, 'D');
118 chunk_put(&c, 'E');
119 chunk_put(&c, 'F');
120 chunk_put(&c, 'G');
121
122 printf("head: %d -- tail: %d -- size: %d\n", c.head, c.tail, chunk_size(&c));
123 return 0;
124}
125