【发布时间】:2021-01-16 14:51:44
【问题描述】:
代码实现了这些功能:
-
check():检查输入的单词是否在字典文件中, -
load():将整个字典加载到哈希表中, -
hash():散列一个词, -
size():返回整个字典的大小和 -
unload():释放load()中使用的所有内存。
问题在于函数load()只将文件字典中的第一个单词加载到哈希表中。
这是故障功能
// Represents a node in a hash table. length being the largest word in the dictionary
typedef struct node {
char word[LENGTH + 1];
struct node *next;
} node;
// Number of hashes in hash table represent the alphabet
const unsigned int N = 26;
// a count variable to pass to the size function
int count = 0;
// Hash table
node *table[N];
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary) {
int b = 0;
char *c = malloc((LENGTH + 1) * sizeof(char));
FILE *f = fopen(dictionary, "r");
while (fscanf(f, "%s", c) != EOF) {
// b is the hash number
b = hash(c);
if (table[b] == NULL) {
node *n = malloc(sizeof(node));
if (n == NULL) {
return false;
}
strcpy(n->word, c);
n->next = NULL;
table[b] = n;
count++;
return true;
} else
if (table[b] != NULL) {
node *n = malloc(sizeof(node));
if (n == NULL) {
return false;
}
strcpy(n->word, c);
n->next = table[b];
table[b] = n;
count++;
return true;
}
}
return false;
}
【问题讨论】:
-
创建第一个节点后,你
return true,从而打破了输入循环。相反,只有在遇到错误时才返回 false,否则在关闭文件后最后返回 true。 -
您是否意识到
if (table[b] == NULL) {...}和else if (table[b] != NULL) {...}中的代码完全相同? -
您可以简化将节点添加到表中。 if 和 else 的逻辑完全一样。保留其他代码,因为您需要这一行:
n->next = table[b];。while(fscanf(f, "%s", c) == 1)是一个更好的循环条件。它更笼统,如果出于任何原因没有读取任何内容,它将是错误的。 -
我删除了 return true 语句,因为它让我脱离了循环并且它起作用了。非常感谢您的帮助!