哈希表的建立
用除留取余法建立哈希表
H(key)=keyMODp(p<=m)
m:哈希表长度=数组长度除以3/4
p:表示小于等于m的最大素数
下面是用链地址法处理哈希冲突
头文件
#ifndef __head_h_
#define __head_h_
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int date;
struct node *next;
}*node;
node create_node();
void init(node hash[],int n);
int max_prime(int n);
void insert_hash(node hash[],int key,int hash_len);
void output_hash(node hash[],int hash_len);
int search_hash(node hash[],int key,int hash_len);
#endif
自定义函数
#ifndef __head_h_
#define __head_h_
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int date;
struct node *next;
}*node;
node create_node();
void init(node hash[],int n);
int max_prime(int n);
void insert_hash(node hash[],int key,int hash_len);
void output_hash(node hash[],int hash_len);
int search_hash(node hash[],int key,int hash_len);
#endif
ubuntu@ubuntu:hash$ cat test.c
#include "head.h"
void init(node hash[],int n)//n为指针数组长度 将指针数组初始化
{
for(int i=0;i<n;i++)
{
hash[i]=NULL;
}
}
node create_node()
{
node p=(node)malloc(sizeof(struct node));
if(p==NULL)
return NULL;
p->date=0;
p->next=NULL;
return p;
}
int max_prime(int n)
{
for(int i=n;i>=2;i++)//遍历所有小于数组长度的数
{
int count=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2)
return i;
}
}
void insert_hash(node hash[],int key,int hash_len)
{
int s=max_prime(hash_len);//s为小于m的最大素数
int sub= key%s;//确定key的位置
node p=create_node();//创建key在堆区的存储空间
if(p==NULL)
{
printf("插入失败");
return;
}
p->date=key;//p的数据域
if(hash[sub]==NULL)//如果hash[sub]指向null时
{
hash[sub]=p;//将hash[sub]指向p
}
else
{
p->next=hash[sub]->next;//哈希表的头插
hash[sub]->next=p;
}
}
void output_hash(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->date);
p=p->next;
}
printf("NULL\n");
}
}
int search_hash(node hash[],int key,int hash_len)
{
int p=max_prime(hash_len);
int sub=key%p;//确定查找元素的单项链表的位置
node s=hash[sub];
while(s!=NULL)
{
if(s->date==key)
{
return 0;
}
s=s->next;
}
return -1;
}
主函数
#include "head.h"
int main(int argc, const char *argv[])
{
int arr[]={41,54,67,12,121,529,853,999,963,852,555};
int len = sizeof(arr)/sizeof(arr[0]);//计算数组长度
int hash_len =len*4/3;//计算哈希表长度
node hash[hash_len];//创建哈希表==指针数组
init(hash,hash_len);//将哈希表初始化
for(int i=0;i<len;i++)//将数组元素输入哈希表
{
insert_hash(hash,arr[i],hash_len);
}
output_hash(hash,hash_len);
int key;
printf("请输入要查找的值\n");
scanf("%d",&key);
int flag=search_hash(hash,key,hash_len);
if(flag==0)
{
printf("哈希表中存在查找元素\n");
}else
{
printf("哈希表中不存在查找元素\n");
}
return 0;
}