C语言,用hash算法来实现英文字典
下面是我写的代码,用的是线性探测在散列算法来解决冲突,来简单实现英文单词字典。定义了两个结构体数组,wordlist[]用来存放单词,hashtable[]用来存放意思,然后打印hashtable[]里的值,但是运行后,只输出主函数的第一个输出语句,然后就停了。
#include<stdio.h>
#define HASH_LEN 4000000
#define WORD_NO 10
#define M 30
#define FLAG -1
/*-----------------------*预定义两个结构体*-------------------------*/
typedef struct word
{
char *wordname;
int key;
}list;
list wordlist[WORD_NO];
typedef struct hash
{
char *wordmean;
int key;
}hashlist;
hashlist hashtable[HASH_LEN];
/*------------------*初始化wordlist[WORD_NO].wordname*----------------*/
initword()
{
static char *p = NULL;
static int i = 0;
static int j = 0;
static int sum = 0;
wordlist[0].wordname = "abc";
wordlist[1].wordname = "cba";
wordlist[2].wordname = "computer";
wordlist[3].wordname = "love";
wordlist[4].wordname = "thank";
wordlist[5].wordname = "you";
wordlist[6].wordname = "me";
wordlist[7].wordname = "soft";
wordlist[8].wordname = "stone";
wordlist[9].wordname = "xin";
for(i =0; i < WORD_NO; i++ )
{
p = wordlist[i].wordname;
for(j = 0;*(p+i)!= '\0'; j++)
{
sum = sum + *(p+i);
}
wordlist[i].key = sum;
}
}
/*------------------*初始化hashtable[HASH_LEN]*----------------*/
inithashtable()
{
static int i = 0;
static int j = 0;
for(i = 0;i < HASH_LEN; i++)
{
hashtable[i].key = FLAG;
hashtable[i].wordmean = "";
}
}
/*----------------------*哈希函数*--------------------------------*/
int h(int k)
{
k = (k+1) % M;
return k;
}
/*---------------------*计算ASCII码值并将单词意思付给hashtable[]*---------------------------*/
askl()
{
int i = 0;
int addr = 0;
int d = 0;
for(i = 0; i < WORD_NO; i++)
{
addr = (wordlist[i].key & 0x7FFFFFFF)% M;
d = addr;
if(hashtable[addr].key == FLAG)
{
hashtable[addr].key = wordlist[i].key;
hashtable[addr].wordmean = wordlist[i].wordname;
}
else
{
do
{
addr = h(addr);
if(addr == d)
{
printf("man le \n");
break;
}
}while(hashtable[addr].key!=FLAG) ;
hashtable[d].key = wordlist[i].key;
hashtable[d].wordmean = wordlist[i].wordname;
}
}
for(i = 0; i< HASH_LEN; i++)
{
printf("%d\n",hashtable[i].key);
printf("%d\n",hashtable[i].wordmean);
}
}
main()
{
printf("++++++++++++++++++++++++++++++++\n");
initword();
printf("--------------------------------\n");
inithashtable();
printf("********************************\n");
askl();
printf("*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
}
请大家看一下,如果有实现的把代码发一发啊,来学习一下。谢谢咯!