广工anyview数据结构习题第四章,
在学习过程中部分题目参考了Giyn 、戮漠、雁过留痕等大佬的代码,在此感谢。
题目解法不是最优解,但希望能给大家有所启发。同时也发了文档资源,需要可自取。
如果对你有帮助,可以给卑微的博主留个赞、关注、收藏 (不是)
(骗一下数据,说不定以后面试就过了,拜谢)
目录
DC04PE04
【题目】已知某哈希表的装载因子小于1,哈希函数H(key)为关键字(标识符)的第一个字母在字母表中的序号,处理冲突的方法为线性探测开放定址法。试编写一个按第一个字母的顺序输出哈希表中所有关键字的算法。哈希表的类型HashTable定义如下∶
#define SuCCESS1
#define UNSUCCESS 0
#define DUPLICATE -1
typedef char StrKeyType[4];
typedef struct {
StrKeyType key;// 关键字项
int tag; //标记 0∶空; 1∶有效; -1∶己删除
void *any; //其他信息
}RcdType2;
typedef struct {
RcdType2 *rcd; //存储空间基址
int size; // 哈希表容量
int Count; //表中当前记录个数
}HashTable;
实现下列函数∶
void PrintKeys(HashTable ht,void(*print)(StrKeyType));
/* 依题意用print输出关键字*/
#include "allinclude.h" //DO NOT edit this line
void PrintKeys(HashTable ht, void(*print)(StrKeyType)){
/* 请调用形参中的print函数输出关键字 */
int i,j=0,num,tem;
StrKeyType temp[ht.count];
for(i=0;i<ht.size;i++)
{
if(ht.rcd[i].tag==1)
strcpy(temp[j++],ht.rcd[i].key);
}
num=j;
StrKeyType s;
for(i=1;i<num;i++)
{ tem=i-1;
for(j=i;j<num;j++)
{
if(temp[j][0]<temp[tem][0])
tem=j;
}
if(tem!=i-1)
{
strcpy(s,temp[i-1]);
strcpy(temp[i-1],temp[tem]);
strcpy(temp[tem],s);
}
}
for(i=0;i<num;i++)
print(temp[i]);
}
DC04PE15
【题目】假设哈希表长为m,哈希函数为H(x),用链地址法处理冲突。试编写输入一组关键字并建造哈希表的算法。哈希表的类型ChainHashTab定义如下∶
#define NUM 7
#define NULLKEY -1
#define SUCCESS 1
#define UNSUCCESS 0
#define DUPLICATE -1
typedef char HKeyType;
typedef struct HNode {
HKeyType data;
struct HNode* next;
}*HLink;
typedef struct {
HLink *rcd;//指针存储基址,动态分配数组
int count; // 当前表中含有的记录个数
int size; // 哈希表的当前容量
}ChainHashTab;//链地址哈希表
/*以下函数可以直接调用*/
int Hash(ChainHashTab H,HKeyType k){ //哈希函数
return k %H.size;
}
Status Collision(ChainHashTab H,HLink &p){
//求得下一个探查地址p
if (p && p->next){
p= p->next;
return SUCCESS;
} else return UNSUCCESS;
}
实现下列函数∶
int BuildHashTab(ChainHashTab &H,int n,HKeyType es[ ]);/* 下列函数可以直按调用
/*哈希函数∶*/
/*int Hash(ChainHashTab H,HKeyType k); */
/*冲突处理函数∶ */
/*int Collision(ChainHashTab H,HLink &p); */
#include "allinclude.h" //DO NOT edit this line
int BuildHashTab(ChainHashTab &H, int n, HKeyType es[])
{ // Add your code here
int i,num,stat;
HLink temp;
if(n==0)
return UNSUCCESS;
//初始化
H.rcd = (HLink*)malloc(H.size * sizeof(HLink));
H.count = 0;
for (i = 0; i < H.size; i++)
{
H.rcd[i] = NULL;
}
for (i = 0; i < n; i++)
{ stat=UNSUCCESS;
num = Hash(H, es[i]); //哈希地址
temp = H.rcd[num]; //链表头位置
if(temp!=NULL)
{
//搜索哈希地址对应链表
for (stat=SUCCESS;stat==SUCCESS;stat = Collision(H,temp))
{
if (temp->data == es[i]) //元素已经在链表中
{ H.count++;
break;
}
}
}
if(stat==UNSUCCESS) //整个链表搜索完毕,找不到
{
temp= (HNode*)malloc(sizeof(HNode)); //在表头创建结点
temp->data = es[i];
temp->next = H.rcd[num];
H.rcd[num]=temp;
H.count++;
}
}
return SUCCESS;
}