blob: 6cf114d48181c18078a7d57789ba9c695197bd69 (
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define NELEM(x) (sizeof(x) / sizeof(x[0]))
typedef int T;
#define START_MAP_CAPACITY 4
#define CHUNK_CAPACITY 10
struct deque {
T **map;
size_t first_chunk;
size_t last_chunk;
size_t capacity;
};
void
deque_init(struct deque *d)
{
d->first_chunk = 0;
d->last_chunk = 0;
// TODO: Error handling
d->map = calloc(START_MAP_CAPACITY, sizeof *d->map);
if ( d->map != NULL ) {
d->capacity = START_MAP_CAPACITY;
for ( size_t i = 0; i != d->capacity; ++i ) {
d->map[i] = NULL;
}
}
}
void
deque_free(struct deque *d)
{
// free all chunks
for ( size_t i = 0; i != d->capacity; ++i ) {
free(d->map[i]);
}
// free the map itself
free(d->map);
}
static void
grow_map(struct deque *d)
{
const size_t capacity = d->capacity + (d->capacity / 2);
T ** map = calloc(capacity, sizeof *map);
// copy elements
size_t i;
for ( i = 0; i != d->capacity; ++i ) {
map[i] = d->map[(i + d->first_chunk) % d->capacity];
}
// initialize the rest (new) elements with NULL
for ( ; i != capacity; ++i ) {
map[i] = NULL;
}
// free old & assign new map
free(d->map);
d->map = map;
// adjust pointers
d->first_chunk = 0;
d->last_chunk = d->capacity - 1;
// set new capacity
d->capacity = capacity;
}
static void
append_chunk(struct deque *d)
{
size_t next = (d->last_chunk + 1) % d->capacity;
if ( next == d->first_chunk ) { // Resize the map
grow_map(d);
next = d->last_chunk + 1;
}
d->map[d->last_chunk] = calloc(CHUNK_CAPACITY, sizeof **d->map);
d->last_chunk = next;
}
static void
prepend_chunk(struct deque *d)
{
size_t prev = (d->first_chunk + d->capacity - 1) % d->capacity;
if ( prev == d->last_chunk ) {
grow_map(d);
prev = d->capacity - 1;
}
d->map[prev] = calloc(CHUNK_CAPACITY, sizeof **d->map);
d->first_chunk = prev;
}
static void
deque_show(struct deque *d)
{
printf("first: %zu -- last: %zu -- capacity: %zu\n", d->first_chunk, d->last_chunk, d->capacity);
for ( size_t i = 0; i != d->capacity; ++i ) {
printf("%zu(%p) ", i, (void *) d->map[i]);
}
puts("");
}
int
main(void)
{
struct deque c;
deque_init(&c);
deque_show(&c);
append_chunk(&c);
deque_show(&c);
append_chunk(&c);
deque_show(&c);
append_chunk(&c);
deque_show(&c);
prepend_chunk(&c);
deque_show(&c);
append_chunk(&c);
deque_show(&c);
prepend_chunk(&c);
deque_show(&c);
prepend_chunk(&c);
deque_show(&c);
deque_free(&c);
return 0;
}
|