第1关:哈希表初始化
任务描述
本关任务:初始化哈希表满足下面要求。 将关键字序列(7、8、30、11、18、9、14)散列存储到散列表中, 散列函数为: H(key) = (key*3) MOD 7,处理冲突采用线性探测再散列法,要求装填(载)因子为0.7。 初始化的哈希表中元素均为-1。
代码:
/*第一关*/
//初始化一个哈希表,能满足线性探测再散列处理冲突法使用,初始化哈希表元素均为-1,表示该位置为空,可插入
struct hashTable* initHashTable_linear()
{
struct hashTable *h=(struct hashTable *)malloc(sizeof(struct hashTable));
h->maxNum=10;
h->curNum=0;
h->element=(int *)malloc(sizeof(int)*h->maxNum);
for(int i=0;i<h->maxNum;i++){
h->element[i]=-1;
}
return h;
}
//初始化一个哈希表,能满足拉链法处理冲突法使用。初始化哈希表元素为0,用于计算该条链中数据个数,在插入时增加
struct hashTable_link * initHashTable_link()
{
struct hashTable_link *h1=(struct hashTable_link *)malloc(sizeof(struct hashTable_link));
h1->maxNum=10;
struct node *p=(struct node *)malloc(sizeof(struct node));
h1->element=(struct node *)malloc(sizeof(struct node));
for(int i=0;i<h1->maxNum;i++){
p->data=0;
p->next=NULL;
h1->element[i]=*p;
}
return h1;
}
第2关:输出哈希表
任务描述
本关任务: 完成函数,能根据哈希表结构输出哈希表的元素。元素之间以空格隔开
代码:
/*第二关*/
//输出线性探测再散列法构建的哈希表,从下标为0的元素开始输出,每输出一个数据空一格
void printHashTable(struct hashTable *h)
{
for(int i=0;i<h->maxNum;i++)
printf("%d ",h->element[i]);
}
第3关:插入键值(线性探测再散列法处理冲突)
任务描述
本关任务:编写一个能将键值插入哈希表的函数,要求按线性探测再散列法处理冲突)
代码:
/*第三关*/
//哈希函数,h(key) = (key*3) % 7
int hashFun(int key)
{
return (key*3) % 7;
}
//函数功能:计算key的哈希地址,若发生冲突,则使用线性探测再散列的方法查找合适的插入位置下标,并返回该下标
int findPos(struct hashTable *h , int key)
{
int keyvalue=hashFun(key);
if(h->element[keyvalue]==-1){
return keyvalue;
}
else{
while(1){
keyvalue++;
if(keyvalue==h->maxNum) keyvalue=0;
if(h->element[keyvalue]==-1){
return keyvalue;
}
}
}
}
//插入键值函数,若哈希表空间已满,则返回-1,否则返回插入位置下标
int insertKey(struct hashTable *h , int key)
{
if(h->curNum==h->maxNum) return -1;
int keyid=findPos(h,key);
h->element[keyid]=key;
return keyid;
}
建议大家再去了解一下开放定址法解决冲突。