#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Ht_item {
char* key;
char* value;
} Ht_item;
typedef struct HashTable {
Ht_item** items;
int size;
int count;
} HashTable;
Ht_item* create_item(char* key, char* value) {
Ht_item* item = (Ht_item*) malloc(sizeof(Ht_item));
item->key = (char*) malloc(strlen(key) + 1);
item->value = (char*) malloc(strlen(value) + 1);
strcpy(item->key, key);
strcpy(item->value, value);
return item;
}
HashTable* create_table(int size) {
HashTable* table = (HashTable*) malloc(sizeof(HashTable));
table->size = size;
table->count = 0;
table->items = (Ht_item**) calloc(table->size, sizeof(Ht_item*));
for (int i = 0; i < table->size; i++)
table->items[i] = NULL;
return table;
}
void free_item(Ht_item* item) {
free(item->key);
free(item->value);
free(item);
}
void free_table(HashTable* table) {
for (int i = 0; i < table->size; i++) {
Ht_item* item = table->items[i];
if (item != NULL)
free_item(item);
}
free(table->items);
free(table);
}
int hash_function(char* key) {
// Simple hash function: sum of ASCII values of characters in the key
int sum = 0;
for (int i = 0; i < strlen(key); i++) {
sum += key[i];
}
return sum % 10;
}
void ht_insert(HashTable* table, char* key, char* value) {
Ht_item* item = create_item(key, value);
int index = hash_function(key);
Ht_item* current_item = table->items[index];
if (current_item == NULL) {
if (table->count == table->size) {
printf("Insert Error: Hash Table is full\n");
free_item(item);
return;
}
table->items[index] = item;
table->count++;
} else {
// Collision handling is not implemented in this example
}
}
Ht_item* ht_search(HashTable* table, char* key) {
int index = hash_function(key);
Ht_item* item = table->items[index];
if (item != NULL && strcmp(item->key, key) == 0) {
return item;
}
return NULL;
}
void ht_delete(HashTable* table, char* key) {
int index = hash_function(key);
Ht_item* item = table->items[index];
if (item != NULL && strcmp(item->key, key) == 0) {
free_item(item);
table->items[index] = NULL;
table->count--;
}
}