2.18哈希表的创建

1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <math.h>
5 
6 enum passble{FALSE=-1,SUCCESS};
7 typedef int datatype;
8 typedef struct Node
9 {
0     //数据域
1     datatype data;
2     //指针域
3     struct Node *next;
4 }*Hashlist;
5 
6 Hashlist create_hash()
7 {
8     //申请一片空间
9     Hashlist s=(Hashlist)malloc(sizeof(struct Node));
0     if(NULL==s)
1         return s;
2     //格式化
3     s->data=0;
4     s->next=NULL;
5     return s;
6 }
7 
8 int max_prime(int m)
9 {
0     for(int i=m;i>1;i--)
1     {
2         int flag=0;                                                                                      
3         for(int j=2;j<=sqrt(i);j++)
4         {
5             if(i%j==0)
6             {
7                 flag=1;
8                 break;
9             }
0         }
1         if(flag==0)
2             return i;
3     }
4 }
5 int input_hash(int element,Hashlist hash[],int m)
6 {
7     //找到m以下的最大质数
8     int p=max_prime(m);
9     //找到通过哈希函数求出来的地址
0     int sub=element%p;
1     //找到表头
2     Hashlist head=hash[sub];
3     //创建一个s存入数据
4     Hashlist s=create_hash();
5     s->data=element;
6     //判断链表为空
7     if(NULL==head)
8     {
9         //直接存入s
0         head=s;
1         hash[sub]=s;
2         return FALSE;
3     }
4     //若有多个节点
5     s->next=head;
6     head=s;
7     hash[sub]=head;
8     return SUCCESS;
9 }
0 
1 void output_hash(Hashlist hash[],int m)
2 {
3     for(int i=0;i<m;i++)
4     {
5         //输出哈希表地址
6         printf("%d:",i);
7         //定义一个指针指向每个表头
8         Hashlist p=hash[i];
9         while(p)
0         {
1             printf("%d ",p->data);
2             p=p->next;
3         }
4         putchar(10);
5     }
6 }
7 
8 int main(int argc, const char *argv[])
9 {
0     //需要储存的数据
1     int arr[]={25,51,8,22,26,67,11,16,54,41};
2     //确定hash表的m值
3     int len=sizeof(arr)/sizeof(arr[0]);
4     int m=len*4/3;
5     //定义指针数组,指针数为m
6     Hashlist hash[m];
7     //将每个指针都指向NULL,防止野指针
8     for(int i=0;i<m;i++)
9     {
0         hash[i]=NULL;
1     }
2     for(int i=0;i<len;i++)
3     {
4         //引用函数,将每个数据都插入哈希表
5         input_hash(arr[i],hash,m);
6     }
7     //输出
8     output_hash(hash,m);
9     return 0;
0 }
                                                                                                           
                                                                                                           
                                                                                                           
                                                                                                           

运行:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值