体会大师们的智慧-散列表(哈希表)

哈希表关键就是散列函数和冲突解决办法

散列函数构造有这几种(我知道的):

直接定址法、数字分析法、平方取中法、折叠法、除留余数法、随机数法


解决冲突的办法有这几种(我知道的):

开放定址法(本代码采用的办法)、再散列函数法、链地址法


全部代码如下

#include <iostream>

class Hash
{
public:
	Hash();
	int init_hash_table();   //初始化散列表
	int hash(int key);   //散列函数
	int insert_hash(int key);  //插入关键字到散列表
	int search_hash(int key);  //散列表查找关键字
private:
	int count;
	int *elem;
};

int main()
{
	Hash hs;

	hs.init_hash_table();

	int key;

	for (int i = 0; i < 5; ++i)
	{
		std::cout << "请输入要插入的关键字:" << std::endl;
		std::cin >> key;

		hs.insert_hash(key);
	}

	std::cout << "请输入要查找的关键字:" << std::endl;
	std::cin >> key;

	hs.search_hash(key);

	return 0;
}

Hash::Hash() : count(0), elem(NULL)
{
	;
}

int Hash::init_hash_table()
{
	this->count = 7;
	this->elem = new int[7];

	for (int i = 0; i < 7; ++i)
	{
		elem[i] = -9999;
	}

	return 0;
}

int Hash::hash(int key)
{
	return key % 7;
}

int Hash::insert_hash(int key)
{
	int add = hash(key);  //求散列地址

	while (this->elem[add] != -9999)  //如果要插入位置有东西
	{
		add = (add + 1) % 7;  //采用开放定址法的线性测试
	}

	this->elem[add] = key;  //将关键字插入

	return 0;
}

int Hash::search_hash(int key)
{
	int add = hash(key);   //求散列地址

	while (this->elem[add] != key)  //如果不是要查找的关键字
	{
		add = (add + 1) % 7;

		if (this->elem[add] == -9999 || add == hash(key)) //如果这位置没有元素  或者 找了一圈又回到了开头
		{
			std::cout << "error!\n" << std::endl;
			
			return 1;
		}
	}

	std::cout << "要查找的元素为" << elem[add] << "地址为" << add << std::endl;

	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值