//拉链法对hash table的溢出处理
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define MAX_CHAR 10
#define TABLE_SIZE 13
typedef struct element
{
char key[MAX_CHAR];
//other fields
}element ;
typedef struct List
{
element item;
struct List *next;
}List, *pList;
pList hash_table[TABLE_SIZE];
void InitHashTable(pList hash_table[])
{
int i;
for( i=0 ; i<TABLE_SIZE ;i++)
hash_table[i]=NULL;
}
int Transform(char * key)
{
int number=0;
while(*key)
{
number+=*key;
key++;
}
return number;
}
int hash(char *key)
{
return (Transform(key) % TABLE_SIZE );
}
void ChainInsert(element item ,pList hash_table[])
{
int hash_value=hash( item.key);
int i=hash_value;
pList p=(pList) malloc(sizeof(List));
p->item=item;
p->next=NULL;
pList ptr=hash_table[i] ;
if(hash_table[i]==NULL)
hash_table[i]=p;
else
{
while(ptr)
{
if(strcmp(ptr->item.key ,item.key)==0)
{
fprintf(stderr,"the identifier %s exists.\n",item.key);
free(p); //由于没有插入,不能有内存泄露,所以此时释放掉内存空间
return;
}
if(ptr->next==NULL)
break;
ptr=ptr->next;
}
ptr->next=p;
}
}
void DestroyHashTable(pList hash_table[])
{
int i;
for(i=0 ;i<TABLE_SIZE ;i++)
{
pList p=hash_table[i];
while(p)
{
pList q=p->next;
free(p);
p=q;
}
hash_table[i]=NULL;
}
}
int main()
{
InitHashTable(hash_table);
element identifier[20];
strcpy(identifier[0].key,"for");
strcpy(identifier[1].key,"do");
strcpy(identifier[2].key,"while");
strcpy(identifier[3].key,"if");
strcpy(identifier[4].key,"else");
strcpy(identifier[5].key,"function");
int i;
for(i=0;i<6;i++)
ChainInsert( identifier[i] ,hash_table);
pList p;
for(i=0;i<TABLE_SIZE;i++)
{
printf("%d. ", i); //为了打印结果漂亮
p=hash_table[i];
while(p)
{
printf("%s ", p->item.key);
p=p->next;
}
printf("\n");
}
ChainInsert( identifier[1] ,hash_table);
strcpy(identifier[7].key,"int");
strcpy(identifier[8].key,"double");
strcpy(identifier[9].key,"float");
strcpy(identifier[10].key,"extern");
strcpy(identifier[11].key,"char *");
strcpy(identifier[12].key,"auto");
strcpy(identifier[13].key,"continue");
strcpy(identifier[14].key,"break");
strcpy(identifier[15].key,"static");
for(i=7;i<=15;i++)
ChainInsert( identifier[i] ,hash_table);
for(i=0;i<TABLE_SIZE;i++)
{
printf("%d. ", i);
p=hash_table[i];
while(p)
{
printf("%s ", p->item.key);
p=p->next;
}
printf("\n");
}
DestroyHashTable(hash_table);
return 1;
}
hash表的拉链法解决冲突
最新推荐文章于 2023-11-22 19:14:47 发布