c - 在哈希表中插入一个节点

标签 c linked-list hashtable

下面的代码是正确的,但我不明白为什么有两行代码可以工作。我指的是最后一个 else block 。具体来说,我指的是这两行:

newWord->next = hashtable[index];
哈希表[索引] = newWord;

如果目标是将节点追加到链表的哈希表索引处,为什么 newWord->next 指向哈希表的索引,因为该索引处可能已经有节点。我认为它应该是 newWord->next = NULL,因为该节点将是链表中的最后一个链接,因此应该指向 NULL。从代码来看,结构的“下一个”字段似乎引用了索引。我希望我说得有道理。 /** * 将字典加载到内存中。如果成功则返回 true,否则返回 false。 */

bool load(const char* dictionary)
{
    // TODO
    // opens dictionary
    FILE* file = fopen(dictionary, "r");
    if (file == NULL)
        return false;

// create an array for word to be stored in
char word[LENGTH+1];

// scan through the file, loading each word into the hash table
while (fscanf(file, "%s\n", word)!= EOF)
{
    // increment dictionary size
    dictionarySize++;

    // allocate memory for new word 
    node* newWord = malloc(sizeof(node));

    // put word in the new node
    strcpy(newWord->word, word);

    // find what index of the array the word should go in
    int index = hash(word);

    // if hashtable is empty at index, insert
    if (hashtable[index] == NULL)
    {
        hashtable[index] = newWord;
        newWord->next = NULL;
    }

    // if hashtable is not empty at index, append
    else
    {
        newWord->next = hashtable[index];
        hashtable[index] = newWord;
    }      
}

最佳答案

您假设新节点附加到末尾是错误的。代码将新节点插入链表的前面,有效地使其成为新的头。 “尾”是旧列表,它的头现在是新头之后的节点。

这种插​​入速度更快,因为您不必遍历列表来找到结尾。节点的顺序在这里无关紧要。

您甚至不需要 if (hashtable[index] == NULL) 中的区别;您可以将这两种情况合并为一种情况,即 else 子句中的代码。

关于c - 在哈希表中插入一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32023260/

相关文章:

swift - 不支持使用符合协议(protocol) AnyObject 的具体类型

c - 程序卡住了,管道文件描述符何时不应该打开?

c - 指向字符串的动态 char 指针数组

c - 并行化错误 MPI_Allgather

c - 在链表程序中维护 'curr'(列表末尾)指针是个好主意吗?

java - 为 Anagrams 制作相同哈希码的错误方法

c# - 来自 Web 服务的哈希表作为 JSON

c - 是否可以使用 C 在 MPI 中使用 MPI_Datatype 发送嵌套结构

oop - 递归调用一个类(实现链表)

java - 没有通过链表获得所需的输出