#ifndef __HEAD_H_
#define __HEAD_H_
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//定义结点
typedef struct Node
{
//数据域
int data;
struct Node *next;
}*node;
#endif
/*
* function: 对哈希表初始化NULL
* @param [ in] 哈希表 哈希表长度
* @param [out]
* @return 无返回
*/
void Init(node hash[],int hash_len)
{
for(int i=0;i<hash_len;i++)
{
hash[i]=NULL;
}
}
/*
* function: 计算p
* @param [ in] 哈希表长度hash_len
* @param [out]
* @return 返回p
*/
int max_prme(int m)//m哈希表长度
{
for(int i=m;i>=2;i--)//循环小于等于m的所有数
{
int count=0;
//判断i是否是素数
for(int j=1;j<=i;j++)//循环所有小于等于i的数
{
if(i%j==0)
{
count++;
}
}
if(count==2)
{
return i;
}
}
}
/*
* function: 创建结点
* @param [ in]
* @param [out]
* @return 成功返回地址失败返回NULL
*/
node create_node()
{
node p=(node)malloc(sizeof(struct Node));
if(p==NULL)
return NULL;
p->data=0;
p->next=NULL;
return p;
}
/*
* function: 把数组元素插入的哈希表
* @param [ in] 哈希表 插入的值
* @param [out]
* @return 无返回值函数
*/
void insert_hash(node hash[],int key,int hash_len)
{
//构建哈希函数
int s=max_prme(hash_len);
int sub=key%s;
//把key存到sub对应的位置
// hash[sub];
//创建新结点p
node p=create_node();
if(p==NULL)
return;
p->data=key;
if(hash[sub]==NULL)
{
hash[sub]=p;
}
else
{
p->next=hash[sub]->next;
hash[sub]->next=p;
}
}
/*
* function: 遍历哈希表
* @param [ in] 哈希表的长度 哈希表
* @param [out]
* @return 无
*/
void output(node hash[],int hash_len)
{
for(int i=0;i<hash_len;i++)//循环每一个链表
{
printf("%d\n",i);
node p=hash[i];
while(p!=NULL)
{
printf("%d\t",p->data);
p=p->next;
}
printf("NULL\n");
}
}
/*
* function: 哈希表查找
* @param [ in] 哈希表 查找的值
* @param [out]
* @return 成功返回0失败返回-1
*/
int search_hash(node hash[],int k,int hash_len)
{
int p=max_prme(hash_len);
int sub=k%p;
node s=hash[sub];
while(s!=NULL)
{
if(s->data==k)
{
return 0;
}
s=s->next;
}
return -1;
}
int main (int argc, const char *argv[])
{
//哈希表:把数据的元素存到哈希表,借助哈希表查找
int arr[]={23,5,467,444,666,775,223,445,45,57};
int len= sizeof(arr)/sizeof(int);
int hash_len=len*4/3;//哈希表的长度
node hash[hash_len];
//防止哈希表是野指针,初始化为NULL
Init(hash,hash_len);
//把数组元素存到哈希表
for(int i=0;i<len;i++)
{
insert_hash(hash,arr[i],hash_len);
}
//遍历哈希表
output(hash,hash_len);
//查找
int k;
printf("请输入你要查找的:\n");
scanf("%d",&k);
int flag=search_hash(hash,k,hash_len);
if(flag==-1)
{
printf("没找到\n");
}
else{
printf("找到了\n");
}
return 0;
}