SWUST OJ1013: 哈希表(开放定址法处理冲突)

题目描述

采用除留余数法(H(key)=key %n)建立长度为n的哈希表,处理冲突用开放定址法的线性探测。

输入

第一行为哈希表的长度n; 第二行为关键字的个数; 第三行为关键字集合; 第三行为要查找的数据。

输出

如果查找成功,输出关键字所哈希表中的地址和比较次数;如果查找不成功,输出-1。

样例输入

13
11
16 74 60 43 54 90 46 31 29 88 77
16

样例输出

3,1
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
#define INF 0x3f3f3f3f
#define M 100
typedef struct node
{
	int data;
	int count;
}hashtable;
void inserthash(hashtable ha[],int m,int num)
{
	int temp=num%m;
	int i=1;
	if(ha[temp].data==-1)
	{
		ha[temp].data=num;
		ha[temp].count=1;
	}
	else
	{
		while(ha[temp].data!=-1)
		{
			temp=(temp+i)%m;
			i++;
		}
		ha[temp].data=num;
		ha[temp].count=i;
	}
}
void search(hashtable ha[],int m,int k)
{
     int i=1,adr;
     adr=k%m;
     while(ha[adr].data!=-1&&ha[adr].data!=k)
     {
         i++;
         adr=(adr+1)%m;
     }
     if(ha[adr].data==k)
         cout<<k%m<<","<<i;
     else
         cout<<"-1";
} 
void createhash(hashtable ha[],int m,int n,int key[])
{
	for(int i=0;i<m;i++)
	{
		ha[i].data=-1;
		ha[i].count=0;
	}
	for(int i=0;i<n;i++)
	{
		inserthash(ha,m,key[i]);
	}
}
int main()
{
	hashtable ha[M];
	int m,n;
	cin>>m>>n;
	int key[M];
	for(int i=0;i<n;i++)
	{
		cin>>key[i];
	}
	int k;
	cin>>k;
	createhash(ha,m,n,key);
	search(ha,m,k);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值