算法分析与设计及其案例第7章课后习题4答案

C语言中的关键字为:auto、break、case、char、const、continue、default、do、double、else、enun、extern、float、for、goto、if、int、long、register、return、short、signed、sizeof、static、struct、switch、typedef、union、unsigned、void、volatile、while
各记录的散列地址如下:
f(auto)=1、f(break)=2、f(case)=3、f(char)=3、f(const)=3、f(continue)=3、f(default)=4、f(do)=4、f(double)=4、f(else)=5、f(enum)=5、f(extern)=5、f(float)=6、f(for)=6、f(goto)=7、f(if)=9、f(int)=9、f(long)=12、f(register)=18、f(return)=18、f(short)=19、f(signed)= 19、f(sizeof)= 19、f(static)= 19、f(struct)= 19、f(switch)= 19、f(typedef)=20、f(union)=21、f(unsigned)=21、f(void)=22、f(volatile)=22、f(while)=23
散列表如下:
算法分析与设计及其案例第7章课后习题4答案_第1张图片
算法分析与设计及其案例第7章课后习题4答案_第2张图片
算法分析与设计及其案例第7章课后习题4答案_第3张图片
平均查找长度=(1×15+2×9+3×4+4×2+5×1+6×1)/26≈2.46

#include "stdio.h"
#include "string.h"
#define RecordNum 32//定义记录个数
#define HashTableNum 32//定义散列表大小
struct HashType//定义记录类型
{
	char str[80];
	struct HashType *next;
};
int count=0;//定义查找次数
//定义并初始化记录数据
struct HashType HashData[RecordNum]=
 {"auto",NULL,"break",NULL,"case",NULL,"char",NULL,"const",NULL,
"continue",NULL,"default",NULL,"do",NULL,"double",NULL,"else",NULL,
"enum",NULL,"extern",NULL,"float",NULL,"for",NULL,"goto",NULL,"if",
NULL,"int",NULL,"long",NULL,"register",NULL,"return",NULL,"short",
NULL,"signed",NULL,"sizeof",NULL,"static",NULL,"struct",NULL,"switch",
NULL,"typedef",NULL,"union",NULL,"unsigned",NULL,"void",NULL,
"volatile",NULL,"while",NULL};
int HashAddress[HashTableNum];//定义散列地址数组
struct HashType *HashTable[HashTableNum];//定义散列表数组
struct HashType *p,*q;//定义搜索链表指针
void CalculateHashAddress()//根据散列函数计算各记录散列地址,散列函数:f(s)
{
	int i,j,HashSumTemp;
	for(i=0;i<RecordNum;i++)
		HashAddress[i]=HashData[i].str[0]-'a'+1;
}
void CalculateHashTable()//将各记录的指针分布到散列表中
{
	int i;
	for(i=0;i<HashTableNum;i++)//初始化散列表
		HashTable[i]=NULL;
	for(i=0;i<RecordNum;i++)//重新计算散列表
		if(HashTable[HashAddress[i]]==NULL)
			HashTable[HashAddress[i]]=&HashData[i];
		else
		{
			p=q=HashTable[HashAddress[i]];
			while(p!=NULL)
			{
				q=p;
				p=p->next;
			}
			q->next=&HashData[i];
		}
}
//查找记录时,先计算其散列地址
int CalculateSearchRecordHashAddress(char record[])
{
	return record[0]-'a'+1;
}
void SearchRecord()//根据散列地址判断待查找记录的有无
{
	char record[80];
	int  SearchRecordHashAddress;
	printf("\n请输入待查找的记录:");
	gets(record);
	SearchRecordHashAddress=CalculateSearchRecordHashAddress(record);
	p=HashTable[SearchRecordHashAddress];
	while(p!=NULL)
	{
		count++;
		if(strcmp(p->str,record)==0)
		{
			printf("\n成功找到!");
			break;
		}
		else
			p=p->next;
	}
	if(p==NULL)
		printf("\n查无记录!");
	printf("\n查找次数为:%d\n",count);
}
int main()
{
	int i;
	CalculateHashAddress();//计算各记录散列地址
	CalculateHashTable();//记录指针分布到散列表中
	SearchRecord();//查找给定的记录
}

你可能感兴趣的:(算法代码demo,时空置换)