-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.c
More file actions
44 lines (35 loc) · 1.05 KB
/
map.c
File metadata and controls
44 lines (35 loc) · 1.05 KB
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
/**
* Copied from "The C Programming Language" section 6.6 (slightly edited
* function names / struct names)
*/
#include <stdlib.h>
#include <string.h>
#include "map.h"
static unsigned hash_HashMap(char *s) {
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31 * hashval;
return hashval % HASHSIZE;
}
MapNode* get_HashMap(MapNode* hashMap[HASHSIZE], char *s) {
MapNode *np;
unsigned hash = hash_HashMap(s);
for (np = *(hashMap + hash); np != NULL; np = np->next)
if (strcmp(s, np->key) == 0)
return np; /* found */
return NULL; /* not found */
}
MapNode* set_HashMap(MapNode* hashMap[HASHSIZE], char* key, int value) {
MapNode *np;
unsigned hashval;
if ((np = get_HashMap(hashMap, key)) == NULL) { /* not found */
np = (struct MapNode *) malloc(sizeof(*np));
if (np == NULL || (np->key = strdup(key)) == NULL)
return NULL;
hashval = hash_HashMap(key);
np->next = *(hashMap + hashval);
*(hashMap + hashval) = np;
}
np->value = value;
return np;
}