hash表线性探测法

18 篇文章 0 订阅

准备把最近写的一些代码一一贴出来,也算是总结吧。只能怪大学时候写的代码很少,所以读研疯狂写代码,把数据结构里面的所有东西都实现了一遍,包括图论中里面的算法。

//hash table 的线性探测法,进行溢出处理
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_CHAR 10 // 字符串的最大大小
#define TABLE_SIZE 13 //hash table的大小
typedef struct Hash
{
	char key[MAX_CHAR];
	//other fields
}element;
element hash_table[TABLE_SIZE];

void InitHashTable(element ht[])
{
	int i;
	for( i=0 ; i<TABLE_SIZE ;i++)
		ht[i].key[0]='\0';
}

int Transform(char * key)
{
	int number=0;
	while(*key)
	{
		number+=*key;
		key++;
	}
	return number;
}

int hash(char *key)
{
	return (Transform(key) % TABLE_SIZE );
}

void LinearInsert(element item ,element ht[])
{
	int hash_value=hash( item.key);
	int i=hash_value;
	while( ht[i].key[0]!='\0' ) //该散列桶里已有填充
	{
		if(strcmp(item.key ,ht[i].key )==0)//桶里该标识符已存在
		{
			fprintf(stderr,"the identifier %s exists\n",item.key);
			return;
		}
		i=(i+1)%TABLE_SIZE;
		if(i==hash_value)
		{
			fprintf(stderr,"the hash table is full\n");
                        return;
		}
	}
	ht[i]=item;
}

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++)
		LinearInsert( identifier[i] ,hash_table);     
	for(i=0;i<TABLE_SIZE;i++)
		printf("%d. %s\n", i, hash_table[i].key);
        LinearInsert( 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++)
		LinearInsert( identifier[i] ,hash_table); 
        for(i=0;i<TABLE_SIZE;i++)
		printf("%d. %s\n", i, hash_table[i].key);
	return 1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值