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
116
117
118
119
120
121
122
123
124
125
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define NELEM(x) (sizeof(x) / sizeof(x[0]))
typedef int T;
struct chunk {
int head, tail;
T array[8];
};
static void
chunk_init(struct chunk *c)
{
c->head = 0;
c->tail = 0;
}
static bool
chunk_put(struct chunk *c, T data)
{
const int next = (c->head + 1) % NELEM(c->array);
if ( next == c->tail ) /* full? */
return false;
c->array[c->head] = data;
c->head = next;
return true;
}
static bool
chunk_get(struct chunk *c, T *data)
{
if ( c->head == c->tail ) /* empty? */
return false;
const int next = (c->tail + 1) % NELEM(c->array);
*data = c->array[c->tail];
c->tail = next;
return true;
}
static int
chunk_size(struct chunk *c)
{
return (c->head + NELEM(c->array) - c->tail) % NELEM(c->array);
}
static bool
chunk_full(struct chunk *c)
{
return ((c->head + 1) % NELEM(c->array)) == c->tail;
}
static bool
chunk_empty(struct chunk *c)
{
return c->head == c->tail;
}
static T*
chunk_at(struct chunk *c, int idx)
{
if ( idx < 0 || idx >= chunk_size(c) ) /* invalid index? */
return NULL;
return &c->array[(c->head + idx) % NELEM(c->array)];
}
/* ================= */
struct deque {
int head, tail, capacity;
struct chunk **chunks;
};
void
deque_init(struct deque *d)
{
int i;
d->head = 0;
d->tail = 0;
d->capacity = 1;
d->chunks = calloc(d->capacity, sizeof(struct chunk *));
for ( i = 0; i != d->capacity; ++i ) {
d->chunks[i] = malloc(sizeof(struct chunk));
chunk_init(d->chunks[i]);
}
}
int main(void)
{
struct chunk c;
int data;
chunk_init(&c);
chunk_put(&c, '0');
chunk_put(&c, '0');
chunk_get(&c, &data);
chunk_get(&c, &data);
chunk_put(&c, 'A');
chunk_put(&c, 'B');
chunk_put(&c, 'C');
chunk_put(&c, 'D');
chunk_put(&c, 'E');
chunk_put(&c, 'F');
chunk_put(&c, 'G');
printf("head: %d -- tail: %d -- size: %d\n", c.head, c.tail, chunk_size(&c));
return 0;
}
|