#include
#include
#include
#include
#define BUCKETS 200
typedef struct ListElmt_{
char data[15];
struct ListElmt_ *next;
}ListElmt;
typedef struct List_{
int size;
ListElmt *head;
}List;
typedef struct CHTBL_{
int buckets;
unsigned int (*h)(const char *key);
int size;
List *table;
}CHTBL;
unsigned int hashpjw(const char *key)
{
const char *ptr = key;
unsigned int val = 0;
while(*ptr)
{
val = val * 131 + *ptr;
ptr++;
}
return val%BUCKETS;
}
void list_init(List *list)
{
ListElmt *tmp = (ListElmt *)malloc(sizeof(ListElmt));
list->size = 0;
list->head = tmp;
return;
}
void list_destroy(List *list)
{
ListElmt *tmp1 = list->head;
ListElmt *tmp2 = tmp1->next;
while(tmp2)
{
tmp1 = tmp2->next;
free(tmp2);
tmp2 = tmp1;
}
list->size = 0;
}
int chtbl_init(CHTBL *chtbl,int buckets,unsigned int (*h)(const char *key))
{
int i = 0;
chtbl->table = (List *)malloc(buckets * sizeof(List));
if(!chtbl->table)
return -1;
chtbl->buckets = buckets;
for(i=0;ibuckets;i++)
list_init(&chtbl->table[i]);
chtbl->h = h;
chtbl->size = 0;
return 0;
}
void chtbl_destroy(CHTBL *chtbl)
{
int i;
for(i=0;ibuckets;i++)
{
list_destroy(&chtbl->table[i]);
}
free(chtbl->table);
return;
}
int chtbl_lookup(CHTBL *chtbl,char *data)
{
List *list;
ListElmt *tmp;
int bucket;
bucket = chtbl->h(data)%chtbl->buckets;
list = &chtbl->table[bucket];
tmp = list->head;
tmp = tmp->next;
while(tmp)
{
if(strcmp(tmp->data,data))
return 0;
tmp = tmp->next;
}
return 1;
}
int chtbl_insert(CHTBL *chtbl,char *data)
{
List *list;
ListElmt *tmp,*node;
int bucket,retval;
if(chtbl_lookup(chtbl,data)==0)
return 1;
bucket = chtbl->h(data)%chtbl->buckets;
printf("bucket : %d\n",bucket);
list = &chtbl->table[bucket];
tmp = list->head;
node = (ListElmt *)malloc(sizeof(ListElmt));
strcpy(node->data,data);
node->next = tmp->next;
tmp->next = node;
list->size++;
return 0;
}
int main()
{
CHTBL test;
char string[15];
chtbl_init(&test,BUCKETS,hashpjw);
strcpy(string,"abc");
chtbl_insert(&test,string);
strcpy(string,"ccc");
chtbl_insert(&test,string);
strcpy(string,"fsdfdsfgsdg");
chtbl_insert(&test,string);
return 0;
}
阅读(1012) | 评论(0) | 转发(0) |