#include <stdio.h>
#include <malloc.h>
#define MinTableSize 3
typedef struct Cells{
int Element;
int Info;
}Cell[10];
typedef struct HashTbl *HashTable;
struct HashTbl{
int TableSize;
Cell TheCells;
}H;
HashTable InitializeTable(int TableSize);
int Find(int key,HashTable H);
void Insert(int Key,HashTable H);
int Hash(int Key,int TableSize);
int NextPrime(int TableSize);
int NextPrime(int TableSize){
int result = TableSize;
if(TableSize%2 == 0 ){
return ++result;
}else{
return result;
}
}
int Hash(int Key,int TableSize){
int hash = Key % TableSize;
return hash;
}
void Insert(int Key,HashTable H){
int Pos;
Pos = Find(Key,H);
if(H->TheCells[Pos].Info == 0 && H->TheCells[Pos].Info !=1){
H->TheCells[Pos].Info = 1;
H->TheCells[Pos].Element = Key;
}
}
int Find(int Key,HashTable H){
int CurrentPos,NewPos;
int CNum = 0;
NewPos = CurrentPos = Hash(Key,H->TableSize);
while(H->TheCells[NewPos].Info != 0 &&
H->TheCells[NewPos].Element != Key){
if(++CNum%2){
NewPos = CurrentPos + (CNum+1)/2 * (CNum+1)/2;
while(NewPos >= H->TableSize){
NewPos -= H->TableSize;
}
}else{
NewPos = CurrentPos - CNum/2 * CNum/2;
while(NewPos < 0){
NewPos += H->TableSize;
}
}
}
return NewPos;
}
HashTable InitializeTable(int TableSize){
HashTable H;
int i;
if(TableSize < MinTableSize){
printf("散列表太小");
return NULL;
}
H = (HashTable)malloc(sizeof(struct HashTbl));
if(H == NULL){
printf("空间溢出");
}
H->TableSize = NextPrime(TableSize);
if(H->TheCells == NULL){
printf("空间溢出");
}
for(int i = 0;i < H->TableSize;i++){
H->TheCells[i].Info = 0;
}
return H;
}
int main () {
HashTable hash = InitializeTable(5);
int i,j;
for(j = 0;j < hash->TableSize;j++){
printf("输入第%d个数:\n",j);
scanf("%d",&i);
Insert(i,hash);
}
for(j = 0;j < hash->TableSize;j++){
printf("%d ",hash->TheCells[j].Element);
}
}