用链地址法处理冲突,构建哈希表:假设哈希表长为m,哈希函数为H(x),用链地址法处理冲

用链地址法处理冲突,构建哈希表:假设哈希表长为m,哈希函数为H(x),用链地址法处理冲

#include<stdio.h>
#include<stdlib.h>
#define SIZE 12


typedef struct _HashNode
{
int data ;
struct _HashNode *next;
}HashNode;


typedef struct _HashList
{
HashNode * elem[SIZE];
int size;
}HashList;


int Hash(int size,int key)
{
return key%size;
}


HashNode *InsertHash(HashNode *head,int key)
{
if(head == NULL)
{
printf("head  == NULL\n");
HashNode *p = (HashNode *)malloc(sizeof(struct _HashNode));
p->data = key;
p->next =  NULL;
return p;
}
HashNode *ph = head;
while(ph != NULL)
{
if(ph->data == key)
{
return head;
}


if(ph->next == NULL)
{
HashNode *p = (HashNode *) malloc(sizeof(struct _HashNode));
p->data =  key;
p->next =  NULL;
ph->next = p;
return head;
}
else ph = ph->next;
}
}


int main()
{
int a[12] = {19,14,23,1,68,20,84,27,55,11,10,79};  
printf("ok\n");
HashList hashlist;
hashlist.size = SIZE;
int i;
for(i = 0;i<hashlist.size;i++)
{
hashlist.elem[i] = NULL;
}
for(i=0;i<12;i++)
{
int sit = Hash(hashlist.size,a[i]);
printf("sit = %d, a[%d] = %d\n",sit,i,a[i]);
hashlist.elem[sit] = InsertHash(hashlist.elem[sit],a[i]);
}
printf("---------------------------\n");
for(i = 0;i<12;i++)
{
printf("%d: ",i+1);
HashNode *p = hashlist.elem[i];
while(p!=NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值