Skip to content

Commit

Permalink
m
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahmoudkhalef committed Dec 29, 2023
1 parent 94831cf commit 368b957
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
30 changes: 30 additions & 0 deletions 0x1A-hash_tables/0-hash_table_create.c
Original file line number Diff line number Diff line change
@@ -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);
}

45 changes: 45 additions & 0 deletions 0x1A-hash_tables/hash_tables.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#ifndef HASH_TABLES_H
#define HASH_TABLES_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/**
* 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

0 comments on commit 368b957

Please sign in to comment.