【数据结构】哈希表类的C++实现

本文详细介绍了一种基于除留取余法的哈希表实现,包括哈希函数设计、插入与查找操作,并通过具体代码示例展示了如何使用哈希表进行数据存储与检索。

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

大概就是给一堆数据,根据数据的值决定它的储存位置,比如新建一个大小为20的数组,把元素10放在10的位置,15放在15的位置,元素和位置的关系由哈希函数决定,这里用的是除留取余函数。

using namespace std;
#define HASHSIZE 12
#define NULLKEY  -327168

class HashTable
{
private:
	int* elem;//元素指针数组
	int count;//元素个数
public:
	HashTable() { elem = NULL;count = 0; }
	int init();
	int Hash(int key);
	void insert(int key);
	int search(const int &key);
};

int HashTable::init()
{
	count = HASHSIZE;
	elem = new int[HASHSIZE];
	if (elem == NULL)
	{
		cout << "error in makespace\n";
		return -1;
	}
	for (int i = 0;i < HASHSIZE;i++)
	{
		elem[i] = NULLKEY;
	}
	return 0;
}

int HashTable::Hash(int key)
{
	return key % HASHSIZE;//除留余数法
}

void HashTable::insert(int key)
{
	int addr;
	addr = Hash(key);
	while (elem[addr] != NULLKEY)
	{
		addr = Hash(addr + 1);
	}
	elem[addr] = key;
}

int HashTable::search(const int &key)
{
	int addr = NULLKEY;
	addr = Hash(key);
	while (elem[addr] != key)
	{
		addr = Hash(addr + 1);
		if (elem[addr] == NULLKEY || addr == Hash(key))//该地址元素为空或者回到起点
		{
			cout << "no element\n";
			return addr;
		}

	}
	return addr;
}

int main()
{
	HashTable table;
	table.init();
	for (int i = 0;i <HASHSIZE;i++)
	{
		int key = i*3+5;
		table.insert(key);
		cout << key << " ";
	}
	cout << endl;
	
	int add=table.search(10);
	if (add == HASHSIZE)
	{
		cout << "no found" << endl;
	}
	return 0;
}

输入的值是 5 8 11 14 17 20 23 26 29 32 35 38
哈希表中的值是 23, 35, 14, 26, 38, 5, 17, 29, 8, 20, 32, 11
找元素10 并没有找到
找元素20 输出位置 9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值