您的位置:首页 > 其它

第15周 项目2-哈希法组织关键字 链地址法

2015-12-07 16:43 387 查看
/*
文件名称:main.cpp

作者       :王超

完成日期:2015年12月7日

问题描述:用哈希法组织关键字 链地址法

*/

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define N 15
#define M 26
typedef struct node   //定义哈希链表的节点类型
{
char *key;
struct node *next;
} LNode;

typedef struct
{
LNode *link;
} HTType;

int H(char *s)   //实现哈希函数
{
return ((*s-'a'+1)%M);
}

//构造哈希表
void Hash(char *s[], HTType HT[])
{
int i, j;
LNode *q;
for(i=0; i<M; i++)   //哈希表置初值
HT[i].link=NULL;
for(i=0; i<N; i++)   //存储每一个关键字
{
q=(LNode*)malloc(sizeof(LNode));   //创建新节点
q->key = (char*)malloc(sizeof(strlen(s[i])+1));
strcpy(q->key, s[i]);
q->next=NULL;
j=H(s[i]);    //求哈希值
if(HT[j].link==NULL)   //不冲突,直接加入
HT[j].link=q;
else        //冲突时,采用前插法插入
{
q->next = HT[j].link;
HT[j].link=q;
}
}
}

//输出哈希表
void DispHT(HTType HT[])
{
int i;
LNode *p;
printf("哈希表\n");
printf("位置\t关键字序列\n");
printf("---------------------\n");
for(i=0; i<M; i++)
{
printf(" %d\t", i);
p=HT[i].link;
while(p!=NULL)
{
printf("%s ", p->key);
p=p->next;
}
printf("\n");
}
printf("---------------------\n");
}

//求查找成功情况下的平均查找长度
double SearchLength1(char *s[], HTType HT[])
{
int i, k, count = 0;
LNode *p;
for(i=0; i<N; i++)
{
k=0;
p=HT[H(s[i])].link;
while(p!=NULL)
{
k++;   //p!=NULL,进入循环就要做一次查找
if(strcmp(p->key, s[i])==0)   //若找到,则退出
break;
p=p->next;
}
count+=k;
}
return 1.0*count/N;   //成功情况仅有N种
}

//求查找不成功情况下的平均查找长度
double SearchLength2(HTType HT[])
{
int i, k, count = 0;  //count为各种情况下不成功的总次数
LNode *p;
for(i=0; i<M; i++)
{
k=0;
p=HT[i].link;
while(p!=NULL)
{
k++;
p=p->next;
}
count+=k;
}
return 1.0*count/M;   //不成功时,在表长为M的每个位置上均可能发生
}
int main()
{
HTType HT[M];
char *s
= {"if", "while", "for", "case", "do", "break", "else", "struct", "union", "int", "double", "float", "char", "long", "bool"};
Hash(s, HT);
DispHT(HT);
printf("查找成功情况下的平均查找长度 %f\n", SearchLength1(s, HT));
printf("查找不成功情况下的平均查找长度 %f\n", SearchLength2(HT));
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: