Hash表的建立,插入与查找实现(C++)

本文详细介绍了HASH表的基本构建过程,包括初始化、插入和查找功能。通过具体代码示例,展示了如何使用哈希函数计算地址,以及如何进行元素的插入和搜索。适用于初学者理解和实践HASH表的数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文实现了一个基本的HASH表的构建插入和查找过程。主要函数功能如下:

bool InitHashTable(HashTable &H);   //hash表的初始化
int Hash(const int key);   //哈希函数,计算地址
bool InsertHash(HashTable &H, const int key);   //插入新元素
bool SearchHash(HashTable &H, const int key, int &add);   //删除新元素

函数结果示例:

Please input Hash Table size: 8
#1 (q to quite): 56
#2 (q to quite): 89
#3 (q to quite): 23
#4 (q to quite): 46
#5 (q to quite): 81
#6 (q to quite): 2
#7 (q to quite): 6
#8 (q to quite): 8
Enter number you want to find: 81
Find 81 at 2.

完整代码:

#include<iostream>
#define UNLLKEY -32768

using namespace std;

struct HashTable
{
	int *elem;
	int count;
};

int HASHSIZE;

bool InitHashTable(HashTable &H)
{
	cout << "Please input Hash Table size: ";
	cin >> H.count;
	HASHSIZE = H.count;
	H.elem = new int[H.count];
	for (int i = 0; i < H.count; i++)
		H.elem[i] = UNLLKEY;
	return true;
}

int Hash(const int key)
{
	return key%HASHSIZE;
}

bool InsertHash(HashTable &H, const int key)
{
	int add = Hash(key);
	while (H.elem[add] != UNLLKEY)
		add = (add + 1) % HASHSIZE;
	H.elem[add] = key;
	return true;
}

bool SearchHash(HashTable &H, const int key, int &add)
{
	add = Hash(key);
	while (H.elem[add] != key) {
		add = (add + 1) % HASHSIZE;
		if (H.elem[add] == UNLLKEY || add == Hash(key))
			return false;
	}
	return true;
}

void main()
{
	HashTable H;
	InitHashTable(H);
	int temp, i = 0;
	cout << "#" << i + 1 << " (q to quite): ";
	while(i<HASHSIZE&&cin >> temp) {
		InsertHash(H, temp);
		i++;
		if (i == HASHSIZE)
			break;
		cout << "#" << i + 1 << " (q to quite): ";
	}
	cin.clear();
	while (cin.get() != '\n')
		continue;
	cout << "Enter number you want to find: ";
	cin >> temp;
	int add;
	if (SearchHash(H, temp, add))
		cout << "Find " << H.elem[add] << " at " << add << ".\n";
	else
		cout << "There is no " << temp << endl;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值