-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_hash_map_put.c
46 lines (40 loc) · 1.1 KB
/
linked_hash_map_put.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
#include "linked_hash_map_put.h"
void put(struct LinkedHashMap *map, int key, int value) {
struct Entry *elem = (struct Entry *) malloc(sizeof(*elem));
if (elem == NULL) {
printf("Error #1: Memory allocation failure while adding new list element");
exit(1);
}
elem->key = key;
elem->value = value;
elem->before = NULL;
elem->after = NULL;
elem->next = NULL;
int h = hash(key);
elem->hash = h;
int index = indexFor(map, h);
struct Entry *bucket = map->table[index];
if (bucket == NULL) {
map->table[index] = elem;
} else {
while (bucket != NULL) {
if (bucket->hash == h && bucket->key == key) {
bucket->value = value;
return;
}
if (bucket->next == NULL) {
bucket->next = elem;
break;
} else {
bucket = bucket->next;
}
}
}
if (map->head == NULL) {
map->head = elem;
} else {
map->tail->after = elem;
elem->before = map->tail;
}
map->tail = elem;
}