哈希表实验报告

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实习报告

题目:设计一个哈希表,完成相应的建表和查表程序

班级:1503013 姓名:李睿元学号:150****0073完成日期:2016.12.04

一、需求分析

1. 假设人名为中国人名的汉语拼音形式;

2. 待填入哈希表的姓名共有30个,去平均查找长度的上限为2;

3. 哈希函数用除留余数法构造,用伪随机探测再散列法处理冲突;

4. 取读者周围较熟悉的30个人的姓名。

二、概要设计

1. 抽象数据类型的定义:

(1)人名数据表:

typedef struct Node

{

char name[20];

int key;

}Node,NodeList[MAX];

(2)哈希表:

typedef struct hashtable

{

char* name;

int key;

int conflict_time;

}HashTable[hashlen];

(3)变量:

#define P 61//随机数值

#define MAX 30//人数

#define hashlen 61//哈希表长

2. 主要函数的实现:

(1)哈希函数:

int Hash(int key)

(2)关键字获得:

int GetKey(char str[])

(3)文件流中读取姓名:

void GetName(NodeList &L,int i,FILE* fp)

(4)哈希表的初始化:

void InitialHashTable(HashTable &ht)

(5)伪随机探测序列的生成:

void CreatConfilctArray(int n[])

(6)哈希表的生成:

void CreatHashTable(HashTable &ht,NodeList L,int* n)

(7)哈希表的查询:

void SearchHashTable(HashTable ht,int* n,char get_name[])三、详细设计

#include

#include

#include

#define P 61//随机数值

#define MAX 30//人数

#define hashlen 61//哈希表长

typedef struct Node

{

char name[20];

int key;

}Node,NodeList[MAX];

typedef struct hashtable

{

char* name;

int key;

int conflict_time;

}HashTable[hashlen];

int Hash(int key)

{

return key%P;

}

int GetKey(char str[])

{

int t=0;

char *s=str;

while(*s)

{

t += *s;

s++;

}

return t;

}

void GetName(NodeList &L,int i,FILE* fp)

{

/*printf("请以拼音形式输入第%d个姓名:",i);

scanf("%s",L[i].name);

L[i].key=GetKey(L[i].name); */

fscanf(fp,"%s",L[i].name);

L[i].key=GetKey(L[i].name);

//printf("\n");

}

void InitialHashTable(HashTable &ht)

{

int n=0;

while(n

{

ht[n].conflict_time=0;

ht[n].name=NULL;

ht[n].key=0;

n++;

}

}

void CreatConfilctArray(int n[])

{

//n=(int*)malloc(50*sizeof(int));

int i=0,j=0;

while(i<50)

{

n[i]=rand()%(hashlen+1);

for(;j

{

if(n[i]==n[j])

{

j=0;

n[i]=rand()%(hashlen+1);

continue;

}

}

i++;

}

}

void CreatHashTable(HashTable &ht,NodeList L,int* n)

{

//CreatConfilctArray(n);

int i=0;

int t;

while(i

{

t=Hash(L[i].key);

if(ht[t].conflict_time==0)

{

ht[t].name=L[i].name;

ht[t].conflict_time++;

ht[t].key=L[i].key;

printf("姓名:%s key值:%d 表内存储位置:%d\n",L[i].name,L[i].key,t);

}

else

{

int m=0;

int d=(t+n[m])%hashlen;

while(ht[d].conflict_time!=0)

{

ht[d].conflict_time++;

m++;

d=(t+n[m])%hashlen;

}

ht[d].name=L[i].name;

ht[d].conflict_time++;

ht[d].key=L[i].key;

printf("姓名:%s key值:%d 表内存储位置:%d\n",L[i].name,L[i].key,d);

}

i++;

}

}

void SearchHashTable(HashTable ht,int* n,char get_name[])

{

//printf("请输入要查询的姓名:");

//char get_name[20];

int p=-1;

int s_time=1;

相关文档
最新文档