【发布时间】:2015-09-24 16:58:34
【问题描述】:
我是哈希表概念的新手。我正在尝试创建一个非常简单的哈希表来理解这个概念。我已经了解如何为散列目的创建基本散列函数。但是我不明白如何将它链接到表格的其余部分。我对如何开始创建表、创建查找函数、删除表中的条目等感到困惑。
哈希函数看起来像这样found here。
unsigned int hash(hash_table_t *hashtable, char *str)
{
unsigned int hashval;
/* we start our hash out at 0 */
hashval = 0;
/* for each character, we multiply the old hash by 31 and add the current
* character. Remember that shifting a number left is equivalent to
* multiplying it by 2 raised to the number of places shifted. So we
* are in effect multiplying hashval by 32 and then subtracting hashval.
* Why do we do this? Because shifting and subtraction are much more
* efficient operations than multiplication.
*/
for(; *str != '\0'; str++) hashval = *str + (hashval << 5) - hashval;
/* we then return the hash value mod the hashtable size so that it will
* fit into the necessary range
*/
return hashval % hashtable->size;
}
但是我不明白其他部分,比如如何创建表格、查找等等..
有人可以帮助我吗?感谢您的任何帮助。
【问题讨论】:
-
这个问题太宽泛,无法给出一个好的答案,但您可能想了解如何实现单链表。哈希表中的每个桶都可以使用单链表来实现,所以一旦你完成了这个工作,你就可以通过使用一个常量哈希函数(即它总是产生相同的哈希和)来测试你的哈希表,这样所有的结果都在同一个桶。
-
您可以在其他问题stackoverflow.com/q/1138742/3545273中找到一些实现示例