线性探测法
![**设有一组关键字{9,01,23,14,55,20,84,27},采用哈希函数: H(key)=key mod 7 ,表长为 10, 2 2 2 用以下公式探测再散列 Hi=(H(key)+di)mod 10 (di=1 ,2 ,3 ,…,)解决冲突。 要求:对该关键字序列构造哈希表,并计算查找成功的平均查找长度。**](https://i-blog.csdnimg.cn/blog_migrate/db0f4cf529d6240afa13ee0569e04aeb.png)
#include<iostream>
#include<stdio.h>
#define LENGTH 8
#define NUM 10
#define MOD1 7
#define MOD2 10
using namespace std;
typedef int ElemType;
int func(int key,int MOD)
{
return key % MOD;
}
void hash_table(ElemType * p, int key)
{
if(p == NULL) return;
int t = func(key,MOD1);
cout<<key<<" mod "<<MOD1<<" = "<<t<<endl;
while(p[t] != -1)
{
cout<<"("<<t<<"+1)"<<" mod "<<MOD2<<" = "<<func(t+1,MOD2)<<endl;
t = func(t+1,MOD2);
if(t == func(key,MOD1))
{cout<<"哈希表已满"<<endl;return;}
}
p[t] = key;
}
int main()
{
int table[NUM];
int flag[LENGTH] = {75, 33, 52, 41, 12, 88, 66, 27};
for(int i = 0; i < NUM; i++)
table[i] = -1;
for(int i = 0; i < LENGTH; i++)
{
int t = flag[i];
hash_table(table,t);
printf(" ------------------------------------------------------------\n");
printf(" | 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 |\n");
printf(" ------------------------------------------------------------\n");
cout<<t<<" ";
for(int i = 0; i < NUM; i++)
cout<<"| "<<table[i]<<" |";
cout<<endl;
printf(" ------------------------------------------------------------\n");
}
int x,t;
while(cin>>x)
{
t = func(x,MOD1);
if(table[t] == x)
cout<<"1\t"<<t<<"\t"<<table[func(x,MOD1)]<<endl;
else
{
t = func(t+1,MOD2);
for(;table[t] != x && t != func(x,MOD1); t = func(++t,MOD2));
if(t != func(x,MOD1))
cout<<"2\t"<<t<<"\t"<<table[t]<<endl;
else
cout<<"数据不存在"<<endl;
}
}
}
链地址法
#include<iostream>
#define MOD1 7
#define data_num 8
using namespace std;
struct hash_table
{
int data;
hash_table * next = NULL;
};
int hash_num(int key,int mod)
{
return key % mod;
}
void hash_table_create(hash_table * &p,int * flag)
{
if(flag == NULL)
return;
cout<<"过程:"<<endl;
for(int i=0; i < data_num; i++)
{
int t = hash_num(flag[i],MOD1);
cout<<flag[i]<<" mod "<<MOD1<<" = "<<t<<"\t";
if(p[t].data != -1)
{
hash_table * q = &p[t],* r = new hash_table;
r->data = flag[i];
while(q->next != NULL)
q = q->next;
q->next = r;
}
else
p[t].data = flag[i];
hash_table * q = &p[t];
while(q != NULL)
{
cout<<q->data<<" ";
q = q->next;
}
cout<<endl;
}
}
int main()
{
int flag[data_num] = {75, 33, 52, 41, 12, 88, 66, 27};
hash_table * p = new hash_table[MOD1];
if(!p) return 0;
for(int i = 0; i<MOD1; i++)
p[i].data = -1;
hash_table_create(p,flag);
cout<<"结果:"<<endl;
for(int i =0; i<MOD1; i++)
{
cout<<"mod 7 = "<<i<<"\t";
hash_table * q = &p[i];
while(q != NULL)
{
cout<<q->data<<' ';
q = q->next;
}
cout<<endl;
}
}