【发布时间】:2017-09-07 05:09:50
【问题描述】:
尝试使用 smdb 算法创建哈希表(因为我听说不要尝试自己编写哈希表是明智之举。)我确定我做错了。我有没有提到我是 C 的新手?
我的 hashFunction() % size 在第一次调用时首先返回一个像 35 这样的数字,然后在第 2 次调用、第 3 次调用、第 4 次调用...时,它会无限返回 65。我只是将这些数字用作任意示例。在尝试用调试器解决之后,我注意到 hashFunction 返回不同的长整数,但它们都以相同的最后 2 个数字结尾......就像这样......
4460735 4526335 4591935
所以我想这就是为什么当我散列 % size 时,每次都会得到相同的输出。这违背了均匀分布密钥的想法,对吧?
请对我放轻松。我知道 SO 上的人有多野蛮。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char* str;
struct node* next;
}
node;
void insertItem(char* number, node** list);
unsigned long hashFunction(char* str);
int main(void)
{
int size = 100;
int index = 0;
node* buckets[size];
for (int i = 0; i < size; i++)
{
char c = i + 'A';
index = hashFunction(&c) % size;
insertItem(&c, &buckets[index]);
}
}
void insertItem(char* str, node** list)
{
node* newItem = malloc(sizeof(node));
newItem->str = str;
newItem->next = *list;
*list = newItem;
}
unsigned long hashFunction(char* str)
{
//sdbm hash function adapted (incorrectly?) from here: http://www.cse.yorku.ca/~oz/hash.html
unsigned long hash = 0;
int c;
while ((c = *str++))
hash = c + (hash << 6) + (hash << 16) - hash;
return hash;
}
【问题讨论】:
-
也许使用素数作为
size可以提供帮助:stackoverflow.com/q/3980117/1025391 / stackoverflow.com/q/1145217/1025391 ? -
啊——这不是真正的问题。现在我明白了……
-
@moooeeeep 感谢您的提示!我之前读过你是对的,我以后会考虑的。
标签: c hash linked-list