#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct HashTable{
int tableSize;
struct HashBody *body;
};
struct HashBody{
int data;
int state;
};
int nextPrime(int num){
num++;
int i;
while(1){
int q=sqrt(num);
for(i=2;i<=q;i++){
if(num%i==0){
break;
}
}
if(i>q){
return num;
}
num++;
}
}
struct HashTable *createTable(int size){
struct HashTable *H;
H=(struct HashTable *)malloc(sizeof(struct HashTable));
H->tableSize=nextPrime(size);
H->body=(struct HashBody *)malloc(sizeof(struct HashBody)*H->tableSize);
for(int i=0;i<H->tableSize;i++){
H->body[i].state=0;
}
return H;
}
int Hash(int num,int size){
return num%size;
}
int Find(struct HashTable *H,int num){
int pos,Newpos;
int shift=0;
pos=Hash(num,H->tableSize);
Newpos=pos;
while(H->body[Newpos].state!=0&&H->body[Newpos].data!=num){
shift++;
Newpos=pos+shift*shift;
Newpos=Newpos%H->tableSize;
}
return Newpos;
}
void Insert(struct HashTable *H,int num){
int pos;
pos=Find(H,num);
if(H->body[pos].state!=1){
H->body[pos].state=1;
H->body[pos].data=num;
}
}
void Delete(struct HashTable *H,int num){
int pos;
pos=Find(H,num);
if(H->body[pos].state==0){
printf("there is not this num.\n");
}else if(H->body[pos].state==1){
H->body[pos].state=2;
printf("%d delete success.\n",num);
}else{
printf("This num had been deleted.\n");
}
}
void show(struct HashTable *H){
printf("此时哈希表:");
for(int i=0;i<H->tableSize;i++){
if(H->body[i].state==1){
printf("%3d",H->body[i].data);
}else{
printf(" # ");
}
}
}
int main(){
struct HashTable *H;
int n;
n=7;
H=createTable(n);
for(int i=0;i<6;i++){
Insert(H,i+10);
}
Insert(H,21);
show(H);
printf("\n");
Delete(H,10);
Delete(H,21);
show(H);
printf("\n再次插入21\n");
Insert(H,21);
show(H);
return 0;
}