在哈希表中插入节点

时间:2015-08-15 09:07:37

标签: c linked-list hashtable

下面的代码是正确的,但我不明白为什么2行代码有效。我指的是最后一个其他块。具体来说,我指的是这两行:

newWord-> next = hashtable [index];
hashtable [index] = newWord;

如果目标是在散列表的索引处将节点附加到链接列表,那么为什么newWord-> gt;当有可能已经存在于该索引处的节点时,接下来指向散列表的索引。我认为它应该是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;
    }      
}

1 个答案:

答案 0 :(得分:1)

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

这种插​​入更快,因为您不必走列表来查找结尾。这里节点的顺序无关紧要。

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