编程实现哈希存储算法的简单实现实例。
通过编写一个简单的哈希实例来加强对哈希算法的理解。下面实例包括存储与查找算法。拉链法解决冲突问题。
如果时间长了对哈希算法的理论知识不够了解,可以先阅读前面转载的两篇文档:
字符串哈希到整数函数,算法:http://blog.csdn.net/hzhsan/article/details/25552153
Hash算法冲突解决方法分析:http://blog.csdn.net/hzhsan/article/details/25555127
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <string>
using namespace std;
#define BUFF_COUNT 1000
struct Student_info
{
string name;
int age;
};
struct Store_info
{
string key;
struct Student_info stu;
Store_info *pNext;
Store_info()
{
pNext = NULL;
}
~Store_info()
{
Store_info* pTemp;
while (pNext != NULL)
{
pTemp = pNext;
delete pNext;
pNext = NULL;
pNext = pTemp->pNext;
}
}
};
Store_info *buff;
unsigned int BKDRHash(char *str)
{
unsigned int seed = 131; // 31 131 1313 13131 131313 etc..
unsigned int hash = 0;
while (*str)
{
hash = hash * seed + (*str++);
}
return (hash & 0x7FFFFFFF);
}
bool Hash_set(string key, const Student_info& student)
{
unsigned int hash_index = BKDRHash((char*)key.c_str())%BUFF_COUNT;
Store_info *pStore = &buff[hash_index];
while ((pStore->key != key) && (pStore->pNext != NULL)) // if some key exists, store to the link list
{
pStore = pStore->pNext;
}
if (pStore->key == key)
{
pStore->stu = student;
return true;
}
Store_info *pNewStore = new Store_info();
pNewStore->key = key;
pNewStore->stu = student;
pStore->pNext = pNewStore;
return true;
}
Student_info* Hash_get(string key)
{
unsigned int hash_index = BKDRHash((char*)key.c_str())%BUFF_COUNT;
Store_info *pStore = &buff[hash_index];
if ((pStore->key != key) && (pStore->pNext != NULL))
{
pStore = pStore->pNext;
}
if (pStore->key == key)
{
return &pStore->stu;
}
return NULL;
}
int main(int argc, char *argv[])
{
buff = new Store_info[BUFF_COUNT];
Student_info stu1;
stu1.name = “hu”;
stu1.age = 11;
Hash_set(“key1”, stu1);
Student_info stu2 = stu1;
stu2.age = 22;
Hash_set(“key2”, stu2);
Student_info stu3 = stu1;
stu3.age = 33;
Hash_set(“key3”, stu3);
Student_info *pstu = Hash_get(“key2”);
if (pstu == NULL)
{
printf(“ERROR:Get NULL\n”);
}
else
{
printf(“name:%s\nage:%d\n”,pstu->name.c_str(),pstu->age);
}
delete []buff;
return EXIT_SUCCESS;
}