-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-hash_table_set.c
47 lines (37 loc) · 1006 Bytes
/
3-hash_table_set.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
/**
* hash_table_set - adds an element to the hash table
* @ht: The hash table
* @key: The key of the new element
* @value: The value of the new element
*
* Return: 1 on success, 0 on failure
*/
int hash_table_set(hash_table_t *ht, const char *key, const char *value)
{
unsigned long int index = 0;
hash_node_t *new_hash_node = NULL;
hash_node_t *tmp = NULL;
if (!ht || !key || !(*key) || !value)
return (0);
index = key_index((unsigned char *)key, ht->size);
tmp = ht->array[index];
/* check if key exists */
while (tmp && strcmp(tmp->key, key) != 0)
tmp = tmp->next;
/* update value if key already exists */
if (tmp)
{
free(tmp->value);
tmp->value = strdup(value);
return (1);
}
/* add new node if key not found */
new_hash_node = malloc(sizeof(*new_hash_node));
if (!new_hash_node)
return (0);
new_hash_node->key = strdup(key);
new_hash_node->value = strdup(value);
new_hash_node->next = ht->array[index];
ht->array[index] = new_hash_node;
return (1);
}