1
下面的代碼是正確的,但我不明白爲什麼有兩行代碼工作。我指的是最後一個塊。具體來說,我指的是這兩行:在哈希表中插入一個節點
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;
}
}