Created
May 29, 2020 17:04
-
-
Save davixcky/048042e55dfb6596b698510dd7d79bf4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "hash_tables.h" | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
hash_table_t *initialize_hash_table(unsigned int size) | |
{ | |
hash_table_t *hash_table; | |
hash_table = calloc(1, sizeof(hash_table_t)); | |
if (!hash_table) | |
return (NULL); | |
hash_table->size = size; | |
hash_table->buckets = calloc(size, sizeof(node_t *)); | |
if (hash_table->buckets == NULL) | |
{ | |
free(hash_table); | |
return (NULL); | |
} | |
return (hash_table); | |
} | |
unsigned int hash(char *key) | |
{ | |
unsigned int i, hash; | |
for (i = hash = 0; key[i] != 0; i++) | |
hash += (key[i] * (i + 1)); | |
return (hash); | |
} | |
unsigned int get_index(char *key, unsigned int size) | |
{ | |
return (hash(key) % size); | |
} | |
node_t insert_hash(hash_table_t *ht, char *key, char *value) | |
{ | |
// Hacer validaciones | |
unsigned int index; | |
node_t *new_node; | |
new_node = malloc(sizeof(node_t)); | |
new_node->key = strdup(key); | |
new_node->value = strdup(value); | |
new_node->next = NULL; | |
index = get_index(key, ht->size); | |
if (ht->buckets[index] == NULL) | |
ht->buckets[index]->next = new_node; | |
return new_node; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment