hash表的拉链法解决冲突

18 篇文章 0 订阅
//拉链法对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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值