C 在哈希表中插入节点

C 在哈希表中插入节点,c,linked-list,hashtable,C,Linked List,Hashtable,下面的代码是正确的,但我不明白为什么有两行代码可以工作。我指的是最后一个街区。具体而言,我指的是以下两行: newWord->next=哈希表[索引] 哈希表[索引]=新词 如果目标是将节点附加到哈希表索引处的链表中,那么为什么newWord->next指向哈希表的索引,而该索引处可能已经有节点了。我认为应该是newWord->next=NULL,因为该节点将是链接列表中的最后一个链接,因此应该指向NULL。从代码看,结构的“下一个”字段似乎正在引用索引。我希望我说的有道理。 /** *将字典加

下面的代码是正确的,但我不明白为什么有两行代码可以工作。我指的是最后一个街区。具体而言,我指的是以下两行:

newWord->next=哈希表[索引]
哈希表[索引]=新词

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


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

这种插入速度更快,因为不必遍历列表就能找到结尾。节点的顺序在这里并不重要

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

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;
    }      
}