关于哈希表,这里采用链表的形式来给大家初步介绍一下
#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返回下标.
当然,取余只是一种比较简单的哈希函数的方式,现在用的比较多的都是查找字符串,这个可以自己设计,其他都是简单的插入.