-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmap_insert.c
74 lines (66 loc) · 1.81 KB
/
map_insert.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* map_insert.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mihykim <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/06/01 12:35:58 by mihykim #+# #+# */
/* Updated: 2020/06/01 13:28:11 by mihykim ### ########.fr */
/* */
/* ************************************************************************** */
#include "map.h"
# define SUCCESS 1
# define FAILURE 0
static t_node *create_node(const char *key, void *value)
{
t_node *node;
node = malloc(sizeof(t_node));
if (node == NULL)
return (NULL);
node->key = key;
node->value = value;
node->next = NULL;
return (node);
}
unsigned int get_hash(const char *key)
{
unsigned int i;
unsigned int hash;
hash = 0;
i = 0;
while (key[i])
{
hash = (hash * BASE) + key[i];
hash %= BIG_PRIME;
i++;
}
return (hash);
}
int map_insert(t_hash_map *map, const char *key, void *value)
{
t_node *new;
t_node *curr;
unsigned int i;
if (map == NULL || (new = create_node(key, value)) == NULL)
return (FAILURE);
i = get_hash(key);
if (map->map[i] == NULL)
map->map[i] = new;
else
{
curr = map->map[i];
while (curr)
{
if (strcmp(curr->key, key) == 0)
{
free(new);
return (FAILURE);
}
curr = curr->next;
}
curr->next = new;
}
map->size++;
return (SUCCESS);
}