#include <stdio.h>
#include <stdlib.h>
struct list_struct {
void *value;
struct list_struct *next;
};
struct hash_elem {
struct list_struct *values;
struct hash_elem *next;
int key;
};
struct hash_table {
struct hash_elem *first;
int (*hashFun)(void *);
void (*printFun)(void *);
};
struct hash_table *prepareHashTable(int(*hashFun)(void *), void(*printFun)(void *)) {
struct hash_table
*table
= (struct hash_table
*) malloc(sizeof(struct hash_table
)); table->printFun = printFun;
table->hashFun = hashFun;
return table;
}
void add(struct hash_table *hashTable, void *value) {
int hashValue = hashTable->hashFun(value);
if (hashTable->first == NULL) {
hashTable
->first
= (struct hash_elem
*) malloc(sizeof(struct hash_elem
)); hashTable->first->key = hashValue;
hashTable
->first
->values
= (struct list_struct
*) malloc(sizeof(struct list_struct
)); hashTable->first->values->value = value;
return;
}
struct hash_elem *hashElem = hashTable->first;
while (hashElem->key != hashValue) {
if (hashElem->next != NULL)
hashElem = hashElem->next;
else {
hashElem
->next
= (struct hash_elem
*) malloc(sizeof(struct hash_elem
)); hashElem->next->key = hashValue;
hashElem = hashElem->next;
}
}
if (hashElem->values == NULL) {
hashElem
->values
= (struct list_struct
*) malloc(sizeof(struct list_struct
)); hashElem->values->value = value;
return;
}
struct list_struct *listElem = hashElem->values;
while (listElem->next != NULL) {
listElem = listElem->next;
}
listElem
->next
= (struct list_struct
*) malloc(sizeof(struct list_struct
)); listElem->next->value = value;
}
void deleteAll(struct hash_table *hashTable) {
struct hash_elem *hashElems = hashTable->first;
struct hash_elem *hashElems2;
struct list_struct *values2;
struct list_struct *values;
while (hashElems != NULL) {
hashElems2 = hashElems->next;
values = hashElems->values;
while (values != NULL) {
values2 = values->next;
values = values2;
}
hashElems = hashElems2;
}
hashTable->first = NULL;
}
void printValue(struct hash_table *hashTable, void *value) {
int hash = hashTable->hashFun(value);
if (hashTable->first == NULL)
return;
struct hash_elem *tmp = hashTable->first;
while (tmp->key != hash) {
tmp = tmp->next;
if (tmp == NULL)
return;
}
struct list_struct *tmp2 = tmp->values;
while (tmp2 != NULL) {
hashTable->printFun(tmp2->value);
tmp2 = tmp2->next;
}
}
typedef int my_int;
void printInt(void *e) {
my_int *tmp;
tmp = (my_int *) e;
}
int generateHashInt(void *value) {
my_int *tmp;
tmp = (my_int *) value;
return (*tmp) % 2;
}
int main() {
struct hash_table *table = prepareHashTable(generateHashInt, printInt);
int a = 10;
int b = 11;
int c = 12;
add(table, (void *) &a);
add(table, (void *) &b);
add(table, (void *) &c);
printValue(table, (void *) &a);
return 0;
}