hashtable.h
#ifndef __HASETABLE_H__
#define __HASETABLE_H__
#define KEY_SZ 256
typedef char* V_t;
typedef struct HashItem HashItem_t;
typedef HashItem_t* HashItemPos_t;
typedef struct HashTable HashTable_t;
struct HashItem
{
char key[KEY_SZ];
V_t value;
HashItemPos_t next;
};
struct HashTable
{
int tableSize;
int (*hashfunc)(char *key);
HashItemPos_t *items;
};
extern HashTable_t *create_empty_hashtable(const int tableSize,int (*hashfunc)(char *key));
extern HashItemPos_t *find_hashtable(char *key,int flag,HashTable_t *h);
extern void delete_hashitem(HashItemPos_t *pItemPos);
extern void destroy_hashtable(HashTable_t *h);
#endif
hashtable.c
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "hashtable.h"
int _hash_default(char *key)
{
int hashcode = 0;
while(*key != '\0')
hashcode += *key++;
return hashcode;
}
HashTable_t *create_empty_hashtable(const int tableSize,int (*hashfunc)(char *key))
{
HashTable_t *h = (HashTable_t *)malloc(sizeof(HashTable_t));
h->tableSize = tableSize;
if(NULL == hashfunc)
h->hashfunc = _hash_default;
else
h->hashfunc = hashfunc;
h->items = (HashItemPos_t *)malloc(tableSize * sizeof(HashItemPos_t));
for(int i = 0;i < tableSize;i++)
h->items[i] = NULL;
return h;
}
HashItemPos_t *find_hashtable(char *key,int flag,HashTable_t *h)
{
int result;
int hashcode = h->hashfunc(key);
int index = hashcode % h->tableSize;
HashItemPos_t *pItemPos = &h->items[index];
HashItem_t *pNewItem = NULL;
while(NULL != *pItemPos)
{
result = strcmp(key,(*pItemPos)->key);
if(0 == result)
return pItemPos;
else if(result < 0)
break;
pItemPos = &((*pItemPos)->next);
}
if(0 == flag)
return NULL;
pNewItem = (HashItem_t *)malloc(sizeof(HashItem_t));
strcpy(pNewItem->key,key);
pNewItem->next = *pItemPos;
*pItemPos = pNewItem;
return pItemPos;
}
void delete_hashitem(HashItemPos_t *pItemPos)
{
HashItem_t *pItem;
pItem = *pItemPos;
*pItemPos = (*pItemPos)->next;
free(pItem);
return;
}
void destroy_hashtable(HashTable_t *h)
{
HashItemPos_t *pItemPos;
for(int i = 0;i < h->tableSize;i++)
{
pItemPos = &h->items[i];
while(*pItemPos != NULL)
delete_hashitem(pItemPos);
}
free(h);
return;
}