哈希表的初步理解

关于哈希表,这里采用链表的形式来给大家初步介绍一下

#include<iostream>
using namespace std;
class hashnode {
public:
	int value;//保存数组里面的值
	int index;//保存数组的下标
	hashnode* next;//行指针
	hashnode* pear;//列指针
	hashnode()
	{
		value = -1;
		index = -1;
		next = NULL;
		pear = NULL;
	}//构造函数
};
class hashmap {
public:
	friend hashnode;
	hashnode* hashlist(int length=10)
	{
		hashnode* head = new hashnode;
		hashnode* p = head;
		for (int i = 0;i < length;i++)
		{
			hashnode* newnode = new hashnode;
			p->next = newnode;
			p = newnode;
		}
		return head;
	 }//返回哈希表的头结点
	hashnode* hashnodefind(int& setvalue, hashnode* head)
	{
		hashnode* p = head;
		for (int i = 0;i < (setvalue % 10);i++)
		{
			p = p->next;
		}
		return p;
	}
	void  hashvalueset(int& setvalue,int& setindex,hashnode* head)
	{
		hashnode* p = hashnodefind(setvalue, head);
		while (p->pear != NULL)
		{
			p = p->pear;
		}
			if (p->index == -1 || p->value == -1)
			{
				p->index = setindex;
				p->value = setvalue;
		
			}
			else {
				hashnode* newnode = new hashnode;
				p->pear = newnode;
				p = p->pear;
				p->index = setindex;
				p->value = setvalue;		
			}		
	}//将值插入哈希表
	int findvalue(hashnode* head, int findvalue)
	{
		hashnode* p = hashnodefind(findvalue, head);
		while (p != NULL)
		{
			if (p->value == findvalue)
			{
				return p->index;
			}
			p = p->pear;
		}
		return -1;
	}// 在哈希表找到值,并且返回相应的坐标(或者说哈希值)
};
void test()
{
	hashmap* newhashmap = new hashmap;
	hashnode* hashhead = newhashmap->hashlist();
	int matrix[100];
	for (int i = 0;i < 100;i++)
	{
		matrix[i] = i;
		newhashmap->hashvalueset(matrix[i], i, hashhead);
	}
	for (int i = 0;i < 100;i++)
	{
		cout << "\t" << newhashmap->findvalue(hashhead, matrix[i])<<" "<<endl;
	}
}
int main()
{
	test();
	system("pause");
	return 0;
}

这里所有代码,可以看到,对一个整型数组各个数字的值进行取余,来插入哈希表中,每一个哈希结点都有横指针和列指针,通过横指针的移动来访问所对应的列表,从而通过结点的index返回下标.
当然,取余只是一种比较简单的哈希函数的方式,现在用的比较多的都是查找字符串,这个可以自己设计,其他都是简单的插入.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值