我有一段单词,我想将每个单词放入哈希表中,并将它们均匀地分配到桶中。
我的问题是,我有哈希表,并且我已经为节点编写了代码,因为它们看起来是最简单的,但是我该怎么做才能让代码读取文本段落,然后吐出每个节点将单词放入哈希表中?我正在使用 while 循环和 fscanf,但我不知道之后要写什么
while (fscanf(paragraph, "%s", paragraph_word) != EOF)
{
如果有帮助,我的哈希表和节点:
for (int i = 0; i < HASHTABLE_SIZE; i++)
{
hashtable[i] = NULL;
}
if (new_node == NULL)
{
unload();
return false;
}
这是我的哈希函数,是我在网上获得的。
int hash_it(char* word)
{
unsigned int hash = 0;
for (int i=0, n=strlen(word); i<n; i++)
hash = (hash << 2) ^ word[i];
return hash % hashtable_size;
}
问题:如何使用 fscanf 读取段落中的每个单词,然后将它们放入偶数桶的哈希表中?
最佳答案
我们使用哈希表来存储一对东西,经常给出的例子是你存储一个名字,然后你想用它检索他的地址或电话号码...... 但在这里(也许我误解了一些东西,但是?)您想将一个单词存储到哈希表中,但您使用该单词作为索引来检索该单词。 通过我的示例,您会得到类似的结果:
int index = hash_it(some_random_name)
hashtable[index];//this will give you his phone number for example;
但是你的问题
int index = hash_it(some_word_in_paragraph);
hashtable[index];//this will give you the word, but you had it already at
// the time you were passing it to the function hash_it
因此,如果我很好地理解了这个问题,我认为更改您所拥有的数据结构可能会很好;
关于从一段单词创建哈希表和节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51958742/