C 有人能检查我实现哈希表的代码的逻辑吗?
我正在尝试实现一个程序,该程序接收一个.txt文件,该文件由字典中的单词填充,load函数的目标是打开该文件,然后读取它,并将所有单词存储在哈希表中。我对数据结构非常陌生,因此我不确定将单词加载到哈希表中的逻辑C 有人能检查我实现哈希表的代码的逻辑吗?,c,linked-list,hashtable,cs50,C,Linked List,Hashtable,Cs50,我正在尝试实现一个程序,该程序接收一个.txt文件,该文件由字典中的单词填充,load函数的目标是打开该文件,然后读取它,并将所有单词存储在哈希表中。我对数据结构非常陌生,因此我不确定将单词加载到哈希表中的逻辑 // Represents a node in a hash table typedef struct node { char word[LENGTH + 1]; struct node *next; } node; // Number of buckets in ha
// Represents a node in a hash table
typedef struct node {
char word[LENGTH + 1];
struct node *next;
} node;
// Number of buckets in hash table
// N = 2 ^ 13
const unsigned int N = 8192;
// Hash table
node *table[N];
这是加载函数,负责从字典文件中读取所有单词,然后将它们全部加载到哈希表中,当它们被传递到从internet获取的哈希函数djb2时,将在哈希表中确定它们的索引
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary) {
// TODO
const int max_len = LENGTH + 1;
char words[max_len];
int index;
// Initialize the array to NULL
for (int i = 0; i < N; i++) {
table[i] = NULL;
}
// Open the dictionary file
FILE indata = fopen(dictionary, "r")
if (indata == NULL) {
return false;
}
// loop to get the words from the file
while (fgets(words, max_len, indata) != NULL) {
// get the index of the word using the hash function
index = hash(words);
// create a new node and check if the computer has memory
node *newNode = malloc(sizeof(node));
if (newNode == NULL) {
return false;
}
if (table[index] == NULL) {
newNode->word = words;
newNode->next = NULL;
table[index] = newNode;
} else {
newNode->word = words;
newNode->next = table[index];
table[index] = newNode;
}
}
return true;
}
//将字典加载到内存中,如果成功则返回true,否则返回false
布尔加载(常量字符*字典){
//待办事项
const int max_len=长度+1;
字符字[max_len];
整数指数;
//将数组初始化为NULL
对于(int i=0;iword=单词;
newNode->next=NULL;
表[索引]=新节点;
}否则{
newNode->word=单词;
新建节点->下一步=表[索引];
表[索引]=新节点;
}
}
返回true;
}
您的代码中存在多个问题:
中的数组定义使用C99可变长度数组语法。某些编译器不接受此语法。只需写load()
并将char字[LENGTH+1]
作为size参数传递给sizeof words
fgets()代码>
- 数组
的大小定义为word[]
。由于MAXLENGTH+1
无法读取整行,因此这将对文件中包含fgets()
或更多字节的单词造成问题。您可能应该将数组放大,并测试输入行是否被截断MAXLENGTH
- 您不会通过
去除数组中留下的尾随换行符,因此哈希表中的条目将具有尾随换行符,这可能不是您想要的fgets()
- 不能将数组分配给数组:要么让节点持有指向字符串的指针,要么使用
复制单词strcpy()
- 无需测试哈希索引的存储桶中是否已有节点:您只需编写:
strcpy(newNode->word, words); newNode->next = table[index]; table[index] = newNode;
- 从
返回之前,您忘记关闭load()
indata
char words[LENGTH+1]“如果读取换行符,则将其存储在缓冲区中。在缓冲区中最后一个字符之后存储一个终止的空字节(\0
)。”您可能需要索引=哈希(字)%N代码>,但我们需要查看hash()
代码,您还需要描述您看到的错误。