Hash查询实现

我使用的是线性探测法处理冲突解决冲突

#include<iostream>
using namespace std;

typedef int KeyType;
typedef int InfoType;


#define SIZE 13
#define P 13

typedef struct {
	KeyType key;       /*KeyType由用户定义*/
	InfoType otherinfo; /*此类型依赖于应用*/
}NodeType;



typedef NodeType Seqlist[SIZE];

NodeType hasht[SIZE];
void insertHTable(KeyType data)
{
	/*插入hash表*/
	int hash_value = data % P;
	int i;
	// 线性探测法处理冲突	hash_value + i) % P
	for (i = 0; hasht[(hash_value + i) % P].key != 0; ++i);
	hasht[(hash_value + i) % P].key = data;
}

void hashTable(Seqlist R)
{
	/*构建hash表*/ // 结构: 邻接表
	int hash_value;
	for (int i = 0; i < SIZE; ++i)
	{
		cin >> R[i].key;
		insertHTable(R[i].key);
	}
}

int hashSearch(Seqlist R, KeyType K)
{
	//计算hash_value
	int hash_value = K % P;
	//查找hash表
	int i;
	for (i = 0; i < SIZE; ++i)
	{
		if (hasht[(hash_value + i) % P].key == K)
			return (hash_value + i) % P;
	}	
	return -1;
}

int main()
{
	Seqlist R;
	KeyType K;
	//初始化hash表
	for (int i = 0; i < SIZE; ++i)
	{
		hasht[i].key = 0;
	}
	cout << "请输入13个无序整数: " << endl;
	hashTable(R);
	// 打印hash表
	cout << "hash表: " << endl;
	for (int i = 0; i < SIZE; ++i)
	{
		cout << hasht[i].key << " ";
	}
	cout << endl;
	while (1)
	{
		cout << "请输入要查找的整数: ";
		cin >> K;
		cout << "hash查找: " << endl;
		int index = hashSearch(R, K);
		if (index == -1)
		{
			cout << "找不到" << K << endl;
		}
		else
		{
			cout << K << "在下标 " << index << endl;
		}
		cout << endl;
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值