#include
#include
#include
#define TABLE_SIZE 100
typedef struct Entry {
char *key;
char *value;
struct Entry *next;
} Entry;
typedef struct {
Entry *entries[TABLE_SIZE];
} HashTable;
unsigned int hash(const char *key) {
unsigned long int value = 0;
unsigned int i = 0;
unsigned int key_len = strlen(key);
for (; i < key_len; ++i) {
value = value * 37 + key[i];
}
value = value % TABLE_SIZE;
return value;
}
HashTable *create_table() {
HashTable *table = malloc(sizeof(HashTable));
for (int i = 0; i < TABLE_SIZE; i++) {
table->entries[i] = NULL;
}
return table;
}
void set(HashTable *table, const char *key, const char *value) {
unsigned int slot = hash(key);
Entry *entry = table->entries[slot];
if (entry == NULL) {
entry = malloc(sizeof(Entry));
entry->key = strdup(key);
entry->value = strdup(value);
entry->next = NULL;
table->entries[slot] = entry;
} else {
Entry *prev;
while (entry != NULL) {
if (strcmp(entry->key, key) == 0) {
free(entry->value);
entry->value = strdup(value);
return;
}
prev = entry;
entry = entry->next;
}
entry = malloc(sizeof(Entry));
entry->key = strdup(key);
entry->value = strdup(value);
entry->next = NULL;
prev->next = entry;
}
}
char *get(HashTable *table, const char *key) {
unsigned int slot = hash(key);
Entry *entry = table->entries[slot];
if (entry == NULL) {
return NULL;
}
while (entry != NULL) {
if (strcmp(entry->key, key) == 0) {
return entry->value;
}
entry = entry->next;
}
return NULL;
}
int main() {
HashTable *table = create_table();
set(table, "name", "Alice");
set(table, "age", "25");
printf("name: %sn", get(table, "name"));
printf("age: %sn", get(table, "age"));
return 0;
}