-
Notifications
You must be signed in to change notification settings - Fork 2
/
map.c
97 lines (88 loc) · 1.72 KB
/
map.c
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
#include <stdlib.h>
#include "map.h"
int mod(int a, int b) {
int r = a % b;
return r < 0 ? r + b : r;
}
map *map_create_n(int n) {
map *m = (map*)malloc(sizeof(map));
m->size = 0;
m->n = n;
m->b = (bucket**)malloc(sizeof(bucket*) * n);
for (int i = 0; i < m->n; i++) {
m->b[i] = NULL;
}
return m;
}
map *map_create() {
return map_create_n(MAP_NUM_BUCKET);
}
void map_free(map *m) {
for (int i = 0; i < m->n; i++) {
bucket *temp = m->b[i], *next;
while (temp != NULL) {
next = temp->next;
free(temp);
temp = next;
}
}
free(m->b);
free(m);
}
void map_set(map *m, int key, void *value) {
int i = mod(key, m->n);
bucket *temp = m->b[i], *b;
while (temp != NULL) {
if (temp->key == key) {
temp->value = value;
return;
}
temp = temp->next;
}
b = (bucket*)malloc(sizeof(bucket));
b->value = value;
b->key = key;
b->next = m->b[i];
m->b[i] = b;
m->size++;
}
void map_unset(map *m, int key) {
int i = mod(key, m->n);
bucket *temp = m->b[i], *prev = temp;
while (temp != NULL) {
if (temp->key == key) {
if (temp == m->b[i]) {
m->b[i] = temp->next;
} else {
prev->next = temp->next;
}
free(temp);
m->size--;
return;
}
prev = temp;
temp = temp->next;
}
}
void *map_get(map *m, int key) {
int i = mod(key, m->n);
bucket *temp = m->b[i];
while (temp != NULL) {
if (temp->key == key) {
return temp->value;
}
temp = temp->next;
}
return NULL;
}
int map_has(map *m, int key) {
int i = mod(key, m->n);
bucket *temp = m->b[i];
while (temp != NULL) {
if (temp->key == key) {
return 1; // true
}
temp = temp->next;
}
return 0; // false
}