一.题目理解:
将给定的无重复正整数序列插入一个散列表,输出每个输入的数字在表中的位置。
所用的散列函数是 H(key)=key%TableSize,其中 TableSize 是散列表的表长。要求用平方探测法(只增不减,即H(Key)+i2)解决冲突。
注意散列表的表长最好是个素数。如果输入给定的表长不是素数,你必须将表长重新定义为大于给定表长的最小素数。
二.此题与书上代码的差别
1)此题要求输入的表长若为素数,则直接返回这个值。
(若返回大于N 且 不超过MAXTABLESIZE的最大素数:将p=N改为p=N+1)
2)平方探测法只增不减:即只有奇数次冲突,且别忘了最后加break(否则无法跳出循环)
三.小知识点
1)Hash函数初始散列地址,根据散列函数来初始
2)scanf加&!!!!!!!!!
四.代码
#include <stdio.h>
#include <math.h>
#include <malloc.h>
#include <stdbool.h>
#define MAXTABLESIZE 10007
typedef int ElementType;//关键词类型
typedef int Index;//散列地址类型
typedef Index Position;//数据所在位置与散列地址是同一类型
typedef enum{
Legitimate,Empty,Deleted
}EntryType;
typedef struct HashEntry Cell;
struct HashEntry{
ElementType Data;
EntryType Info;//单元状态
};
typedef struct TblNode *HashTable;
struct TblNode{
int TableSize;
Cell *Cells;//存放散列单元数据的数组
};
int NextPrime(int N)
{
int i,p;
for(p=N;p<MAXTABLESIZE;p++){
for(i=2; i<=p; i++){
if(p%i== 0) break;
}
if(i>=p) return p;
}
}
HashTable CreatTable(int TableSize)
{
HashTable H;
int i;
H=(HashTable)malloc(sizeof(struct TblNode));
H->TableSize =NextPrime(TableSize);
H->Cells =(Cell *)malloc(H->TableSize*sizeof(Cell));
for(i=0;i<H->TableSize ;i++){
H->Cells[i].Info =Empty;
}
return H;
}
int Hash(ElementType Key,int TableSize)
{
return Key%TableSize;
}
Position Find(HashTable H,ElementType Key)
{
Position CurrentPos,NewPos;
int CNum=0;//记录冲突次数
NewPos=CurrentPos=Hash(Key,H->TableSize );
while(H->Cells[NewPos].Info !=Empty && H->Cells[NewPos].Data !=Key){
if(++CNum%2){//只+i平方,即只有奇数次冲突
NewPos =CurrentPos+(CNum+1)*(CNum+1)/4;
if(NewPos>=H->TableSize ){
NewPos = NewPos%H->TableSize;
break;
}
}
}
return NewPos;
}
int flag=1;//输出
bool Insert(HashTable H,ElementType Key)
{
Position Pos=Find(H,Key);
if(H->Cells[Pos].Info !=Legitimate){
H->Cells[Pos].Info =Legitimate;
if(flag){
H->Cells[Pos].Data =Key;
printf("%d",Pos);
flag=0;
}
else{
H->Cells[Pos].Data =Key;
printf(" %d",Pos);
}
return true;
}
else{
if(flag){
printf("-");
flag=0;
}
else{
printf(" -");
}
return false;
}
}
int main()
{
int MSize,N,i,Key;
scanf("%d %d",&MSize,&N);
HashTable H=CreatTable(MSize);
for(i=0;i<N;i++){
scanf("%d",&Key);
Insert(H,Key);
}
return 0;
}