#ifndef _SIMPLE_HASH_TABLE_
#define _SIMPLE_HASH_TABLE_
typedef struct _hashnode {
int m_index;
struct _hashnode* m_link;
} hashnode_t;
typedef int (* hashfunc_t) (int node);
typedef struct _hashtable {
hashfunc_t m_func;
hashnode_t** m_data;
int m_len;
} hashtable_t;
hashnode_t* hashtable_find (hashtable_t* tab, int index);
void hashtable_init (hashtable_t** tab, hashfunc_t func, int len);
void hashtable_insert (hashtable_t* tab, hashnode_t* node);
void hashtable_remove (hashtable_t* tab, int node);
void hashtable_display (hashtable_t* tab);
void hashtable_destroy (hashtable_t** tab);
#endif
#include "simpleht.h"
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void hashtable_init (hashtable_t** tab, hashfunc_t func, int len) {
int i = 0;
*tab = (hashtable_t*)malloc(sizeof(hashtable_t*));
(*tab)->m_data = (hashnode_t**)malloc(sizeof(hashnode_t*)*len);
(*tab)->m_func = func;
(*tab)->m_len = len;
for (i = 0; i < len; ++i) {
(*tab)->m_data[i] = 0;
}
}
void hashtable_insert (hashtable_t* tab, hashnode_t* node) {
int hashnum;
hashnode_t **tail;
hashnum = tab->m_func (node->m_index);
tail = &tab->m_data[hashnum];
while (*tail) {
tail = &(*tail)->m_link;
}
*tail = node;
}
void hashtable_remove (hashtable_t* tab, int nodeindex) {
int hashnum;
hashnode_t **tail, *tmp;
hashnum = tab->m_func (nodeindex);
tail = &tab->m_data[hashnum];
while (*tail) {
if ((*tail)->m_index == nodeindex) {
tmp = *tail;
break;
}
*tail = (*tail)->m_link;
}
if (tmp) {
*tail = (*tail)->m_link;
free (tmp);
}
}
void hashtable_display (hashtable_t* tab) {
int i;
hashnode_t* cusor;
for (i = 0; i < tab->m_len; ++i) {
printf ("%d : ", i);
cusor = tab->m_data[i];
while (cusor) {
printf ("%d ", cusor->m_index);
cusor = cusor->m_link;
}
printf ("n");
}
}
void hashtable_destroy (hashtable_t* tab) {
int i;
hashnode_t** cusor, *tmp;
for (i = 0; i < tab->m_len; ++i) {
cusor = &tab->m_data[i];
while (*cusor) {
tmp = *cusor;
*cusor = (*cusor)->m_link;
free (tmp);
}
}
free (tab->m_data);
}
hashnode_t* hashtable_find (hashtable_t* tab, int index) {
int hashnum;
hashnode_t* cusor;
hashnum = tab->m_func (index);
cusor = tab->m_data[hashnum];
while (cusor) {
if (cusor->m_index == index) {
return cusor;
}
cusor = cusor->m_link;
}
return 0;
}
int hashfunc (int index) {
return index % 10;
}
int main () {
hashtable_t* table = 0;
hashtable_init (&table, hashfunc, 10);
for (int i = 0; i < 100; ++i) {
hashnode_t* node = (hashnode_t*) malloc(sizeof(hashnode_t));
node->m_index = rand() % 1000;
node->m_link = 0;
hashtable_insert (table, node);
}
hashtable_display (table);
hashtable_destroy (table);
return 0;
}
输出结果: