From 368b9572eba066a400856234ae2c5f48ba8cb65f Mon Sep 17 00:00:00 2001 From: mahmoudkhalef Date: Fri, 29 Dec 2023 04:29:25 -0800 Subject: [PATCH] m --- 0x1A-hash_tables/0-hash_table_create.c | 30 +++++++++++++++++ 0x1A-hash_tables/hash_tables.h | 45 ++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 0x1A-hash_tables/0-hash_table_create.c create mode 100644 0x1A-hash_tables/hash_tables.h diff --git a/0x1A-hash_tables/0-hash_table_create.c b/0x1A-hash_tables/0-hash_table_create.c new file mode 100644 index 0000000..f6c10b4 --- /dev/null +++ b/0x1A-hash_tables/0-hash_table_create.c @@ -0,0 +1,30 @@ +#include "hash_tables.h" + +/** + * hash_table_create - Creates a hash table. + * @size: The size of the array. + * + * Return: If an error occurs - NULL. + * Otherwise - a pointer to the new hash table. + */ +hash_table_t *hash_table_create(unsigned long int size) +{ + hash_table_t *ht; + unsigned long int i; + + ht = malloc(sizeof(hash_table_t)); + if (ht == NULL) + return (NULL); + ht->array = malloc(sizeof(hash_node_t *) * size); + if (ht->array == NULL) + { + free(ht); + return (NULL); + } + ht->size = size; + for (i = 0; i < size; i++) + ht->array[i] = NULL; + + return (ht); +} + diff --git a/0x1A-hash_tables/hash_tables.h b/0x1A-hash_tables/hash_tables.h new file mode 100644 index 0000000..a233cf4 --- /dev/null +++ b/0x1A-hash_tables/hash_tables.h @@ -0,0 +1,45 @@ +#ifndef HASH_TABLES_H +#define HASH_TABLES_H + +#include +#include +#include + + +/** + * struct hash_node_s - Node of a hash table + * + * @key: The key, string + * The key is unique in the HashTable + * @value: The value corresponding to a key + * @next: A pointer to the next node of the List + */ +typedef struct hash_node_s +{ + char *key; + char *value; + struct hash_node_s *next; +} hash_node_t; + +/** + * struct hash_table_s - Hash table data structure + * + * @size: The size of the array + * @array: An array of size @size + * Each cell of this array is a pointer to the first node of a linked list, + * because we want our HashTable to use a Chaining collision handling + */ +typedef struct hash_table_s +{ + unsigned long int size; + hash_node_t **array; +} hash_table_t; + +hash_table_t *hash_table_create(unsigned long int size); +unsigned long int hash_djb2(const unsigned char *str); +unsigned long int key_index(const unsigned char *key, unsigned long int size); +int hash_table_set(hash_table_t *ht, const char *key, const char *value); +char *hash_table_get(const hash_table_t *ht, const char *key); + +#endif +