SWUST OJ1012: 哈希表(链地址法处理冲突)

题目描述

采用除留余数法(H(key)=key %n)建立长度为n的哈希表,处理冲突用链地址法。建立链表的时候采用尾插法。

输入

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

输出

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

样例输入

13
13
16 74 60 43 54 90 46 31 29 88 77 78 79
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;
	struct node*next;
}LNode;
typedef struct
{
	LNode*firstp;
}hashtable;
void inserthash(hashtable ha[],int m,int num)
{
	int temp=num%m;
	LNode*q=(LNode*)malloc(sizeof(LNode));
	LNode*r;
	q->next=NULL;
	q->data=num;
	if(ha[temp].firstp==NULL)
	{
		ha[temp].firstp=q;
	}
	else
	{
		r=ha[temp].firstp;
		while(r->next!=NULL)
		{
			r=r->next;
		}
		r->next=q;
	}
}
void createhash(hashtable ha[],int n,int m,int key[])
{
	for(int i=0;i<m;i++)
	{
		ha[i].firstp=NULL;
	}
	for(int i=0;i<n;i++)
	{
		inserthash(ha,m,key[i]);
	}
}
void search(hashtable ha[],int n,int m,int k)
{
	int i=0;
	int temp=k%m;
	LNode*q=ha[temp].firstp;
	while(q!=NULL)
	{
		i++;
		if(q->data==k)
		{
			break;
		}
		q=q->next;
	}
	if(q!=NULL)
	{
		cout<<k%m<<","<<i;
	}
	else
	{
		cout<<"-1";
	}
}
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,n,m,key);
	search(ha,n,m,k);
	return 0; 
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值