哈希表-C语言
具体代码
#include<stdio.h>
#define MAXSIZE 20
bool Insert(int hash[MAXSIZE],int e,int length){
if(length<MAXSIZE){
int j = e%MAXSIZE;
while(hash[j] != 0){
j=(++j%MAXSIZE);
}
hash[j] = e;
length++;
return true;
}else{
return false;
}
}
void Print(int hash[MAXSIZE]){
printf("元素:");
for(int i=0;i<MAXSIZE;i++){
printf("%d ",hash[i]);
}
}
int Find(int hash[MAXSIZE],int key){
int j = key%MAXSIZE;
int temp = j;
do{
if(hash[temp]==key){
return temp;
}
temp=(++temp%MAXSIZE);
}while(hash[temp]!=key&&temp!=j);
return -1;
}
int main(){
int hash[MAXSIZE]={0};
int length = 0;
int e,key,get;
while(length<MAXSIZE){
printf("请输入插入元素(结束请插入0):");
scanf("%d",&e);
if(e==0){
break;
} else{
Insert(hash,e,length);
}
}
Print(hash);
while(true){
printf("\n请输入要查找的元素(0结束):");
scanf("%d",&key);
if(key==0){
printf("查找结束");
break;
}else{
get = Find(hash,key);
if(get==-1){
printf("不存在");
}else{
printf("%d",get);
}
}
}
}