-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.c
49 lines (40 loc) · 1001 Bytes
/
hash.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
#include "mr.h"
#include "test.h"
#include "list.h"
#include "util.h"
struct hash_table {
long nbuckets;
struct list **buckets;
};
void hash_table_init(struct hash_table **h, long buckets)
{
int i;
(*h) = (struct hash_table*)mapmem(sizeof(struct hash_table));
(*h)->nbuckets = buckets;
(*h)->buckets =
(struct list**)mapmem(sizeof(struct list *) * buckets);
for (i = 0; i < buckets; i++) {
list_init(&(((*h)->buckets)[i]));
}
}
void hash_table_destroy(struct hash_table **h)
{
int i;
for (i = 0; i < (*h)->nbuckets; i++) {
list_destroy(&(((*h)->buckets)[i]));
}
free((*h)->buckets);
free(*h);
}
int hash_search(struct hash_table *h, long key)
{
return search(h->buckets[key % h->nbuckets], key);
}
int hash_delete(struct hash_table *h, long key)
{
return delete(h->buckets[key % h->nbuckets], key);
}
int hash_insert(struct hash_table *h, long key)
{
return insert(h->buckets[key % h->nbuckets], key);
}