-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-hash_table_set.c
47 lines (44 loc) · 1.02 KB
/
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
#include "hash_tables.h"
/**
* hash_table_set - sets a value to the hash_key
* @ht: the pointer hash table
* @key: the key
* @value: the value to insert at a given key
* Return: 1(success) or 0(failed)
*/
int hash_table_set(hash_table_t *ht, const char *key, const char *value)
{
unsigned long int index;
hash_node_t *newnode;
hash_node_t *current;
if (!ht || !key || !value || strcmp(value, "") == 0)
return (0);
index = key_index((const unsigned char *)key, ht->size);
current = ht->array[index];
while (current)
{
if (strcmp(current->key, key) == 0)
{
free(current->value);
current->value = strdup(value);
if (!current->value)
return (0);
return (1);
}
current = current->next;
}
newnode = malloc(sizeof(hash_node_t));
if (!newnode)
return (0);
newnode->key = strdup(key);
newnode->value = strdup(value);
if (!newnode->key || !newnode->value)
{
free(newnode->key);
free(newnode->value);
free(newnode);
}
newnode->next = ht->array[index];
ht->array[index] = newnode;
return (1);
}