【发布时间】:2015-11-08 11:43:54
【问题描述】:
下面的代码是正确的,但我不明白为什么 2 行代码有效。我指的是最后一个 else 块。具体来说,我指的是这两行:
newWord->next = hashtable[index];
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;
}
}
【问题讨论】:
标签: c linked-list hashtable