function bkd(ss:string):longint//哈希函数
var i:longint
begin
bkd:=0
for i:=1 to length(ss) do
bkd:=((bkd*131+ord(ss[i])) and $FFFFFFF) mod 999997
end
function find(ss:string):longint//查找 *** 作
var j:longint
begin
j:=hash[num]//哈希表的头指针
while (j>0) and (list[j]<>ss) do j:=next[j]//拉链探测,相当于一个桶来处理冲突
exit(j)//返回卜纤在线性表中的位置
end
procedure insert(ss:string)//插入 *** 作,SS为插入元素型蠢仿,以字符串的形式存储
var j:longint
begin
inc(loc)
list[loc]:=ss//线性表
next[loc]:=hash[num]//链到对应哈希值的桶上
hash[num]:=loc
end
哈希值计算档悔:NUM:=BKD(SS) MOD OOoo就是你要除余得数
#include <stdio.h>#include <string.h>
#include <stdlib.h>
#define N 100//散列表长度
struct Node
{
char* keychar* val
Node* next
}*heads[N]//散列表,用链处理冲突
int hash(char* key)//散列函数
{
unsigned long h=0
while(*key)
{
h=(h<<4)+*key++
unsigned long g=h &0xF0000000L
if(g)
h^=g>>24
h&=~g
}
return h&N
}
Node* find(char* key)//查找
{
Node* cur=heads[hash(key)]
while(cur)
{
if(!strcmp(cur->key,key))
return cur
cur=cur->next
}
return NULL
}
void insert(char* key,char* val)//插核颂塌入
{
int i=hash(key)
Node* head=heads[i]
if(find(key)==NULL)
{
Node* tmp=(Node*)malloc(sizeof(Node))
tmp->key=(char*)malloc(strlen(key)+1)
tmp->val=(char*)malloc(strlen(val)+1)
strcpy(tmp->key,key)
strcpy(tmp->val,val)
tmp->next=head
heads[i]=tmp
}
}
main()
{
char tmp[100],*key,*val
Node* cur
FILE *fp=fopen("abc.txt","r")
if(fp==NULL)
{
printf("打开文件有问题\n"樱团)
exit(1)
}
while(fgets(tmp,100,fp)!=NULL)
{
if(tmp[strlen(tmp)-1]=='\n')
tmp[strlen(tmp)-1]='\0'
key=strtok(tmp,"\t")
val=strtok(NULL,"\t")
insert(key,val)
}
printf("输入你要查找的单词:\n")
while(gets(tmp))
{
cur=find(tmp)
if(cur==NULL)
printf("没找到\n"改圆)
else
printf("%s\n",cur->val)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)