拉链法
Hash(KEY) = Positon;
在Postion下面形成一个单链表,存储所有以该Positon为存储地址的数据。
找一个比数据范围略大的大质数
例如数据范围是10W
for(int i = 100000; ; i++)
{
bool bFlag = true;
for(int j = 2; j * j <= i; j++)
{
if(0 == i % j)
{
bFlag = false;
break;
}
}
if(bFlag)
{
cout<<i<<endl;
break;
}
}
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 100003;//大质数 用来求哈希地址
int Head[N];//用来存储每个哈希地址的首节点地址
int Value[N]; //存储值
int Next[N];//存储链表的下一个地址
int nPos; //记录存储位置
void Insert(int nNum)
{
int nKey = ((nNum % N) + N) % N;//是为了防止nNum是负数
Value[nPos] = nNum;//记录下数值
//链表的头插法
Next[nPos] = Head[nPos];
Head[nPos] = nPos;
nPos++;
}
void Find(int nNum)
{
int nKey = ((nNum % N) + N) % N;
int nPos = Head[nKey];
while(-1 != nPos)
{
if(nNum == Value[nPos])
{
cout<<"查找到了 "<<endl;
return;
}
else
{
nPos = Next[nPos];
}
}
cout<<"查不到"<<endl;
}
int main(int argc, char** argv)
{
memset(Head,-1,sizeof(Head));
Insert(0);
Find(0);
Insert(1);
Find(111);
return 0;
}