免责声明:这是一个家庭作业问题。应该很明显,我正在尝试自己解决它。我似乎遇到了一个我无法弄清楚的问题,因此我们将不胜感激。
我需要散列一组单词,并将其插入到链表数组中。因此,如果 3 个不同的单词具有哈希 38,则在数组 [38] 处,我需要一个包含 3 个单词的链表。
我正在使用这个结构
struct Word {
char* word;
struct Word* next;
};
哈希后,我将它插入到数组中,如下所示:
struct Word* table[1000]; // array of linked-lists
char word[128];
while(fgets(word, sizeof(word), dict) != NULL) {
hashValue = hashWord(word, strlen(word));
struct Word *newWord = malloc(sizeof(struct Word));
newWord->word = word;
if (table[hashValue] == NULL) {
table[hashValue] = newWord;
} else { // at index hashValue, table already contains at least one element
// insert new word as first element of linked-list
newWord->next = table[hashValue];
table[hashValue] = newWord;
}
}
我知道大约有 5 个单词的哈希值为 38,但是当我打印它们时,我得到了 5 次相同的单词:
struct Word* foo = table[38];
while (foo->next != NULL) {
printf("%s", foo->word); // prints the same word every time
foo = foo->next;
}
似乎我在某个时候覆盖了我的链接列表,但我不知道在哪里。