哈希表的编程

 
 
#include<stdio.h>
#include<malloc.h>
#define keynum 32  //要存放的元素个数

//哈希结点
struct HashAddress
{
	int key; //存放元素
	int flag;  // 是否存放元素标示
};
//哈希表初始化
void intailHash(HashAddress * wh,int n)
{
	   for(int i=0;i<n;i++)  
	   
		   wh[i].flag=-1;
}
//把元素放进哈希表中
//m n分别表示 哈希表长度,与元素规模通常m=2*n时,较合理
//这里哈希函数为KEY%m,解决冲突办法是+1
void CreatHash(HashAddress *wh,int m,int *A,int n)
{
	int place;
	for(int i=0;i<n;i++)
	{
       place=A[i]%m;
	   while(wh[place].flag!=-1)	//	冲突
	   {
		   place=(place+1)%m;     


	   }
	   wh[place].flag=1;	//	元素放入哈希表
	   wh[place].key=A[i];

	}
}

//在长为m哈希表中找元素KEY,找到输出其地址和查找次数
void FindKeyInHash(HashAddress *wh,int m,int key)
{
	int place;
	place=key%m;
	int findtime=0;

	while(wh[place].flag!=-1&&wh[place].key!=key)
	{	 
		place=(place+1)%m;
	   findtime++;
	  }
		printf("found %dth \n",findtime);

    if( wh[place].key==key)	//	找到
	{
		printf("have the key %d \n",place);
           return;
	}
	else if(wh[place].flag==-1)//找不到
	{
		printf("no the key!");
		return;
	}


}


int main()
{
	   
	 int  num[keynum]={15,16,26,75,18,25,27,1,2,9,28,29,19,20,21,22,23,24,30,31,32,10,11,12,13,3,4,5,6,7,8,14};//测试数据 
     
     HashAddress * where=(HashAddress*)malloc(sizeof(HashAddress)*2*keynum);
	 if(NULL==where)
	 {
		 printf("no memroy for hashaddress \n");
		 return -1;
	 }
 intailHash(where,keynum*2);
 CreatHash(where,2*keynum,num,keynum);
 FindKeyInHash(where,2*keynum,75);
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值