没有创建链表,为什么? [CS50 pset4]
Linked lists are not created, why? [CS50 pset4]
我正在做 CS50 的 pset4,它基本上需要您创建 26 个节点(每个节点对应字母表中的每个字母)并在这些节点中创建一个链表以连接字典中的单词。
因此,例如,节点 0 将存储词典中以 A 开头的每个单词,节点 1 将存储词典中以 B 开头的每个单词,等等...
所以,这里是主要的代码:
// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
// for every word, we allocate enough memory for a node, that will carry the word
node *new_node = malloc(sizeof(node));
if(new_node == NULL) { printf("could not allocate memory.\n"); return false; }
strcpy(new_node->word, word);
new_node->next = NULL;
if(!hashtable[alphabetPosition(word[0])]){
hashtable[alphabetPosition(word[0])] = new_node;
}
else
{
for(node *ptr = hashtable[alphabetPosition(word[0])]; ptr != NULL; ptr = ptr->next){
hashtable[alphabetPosition(word[0])]->next = new_node;
}
}
}
alphabetPosition() 基本上是一个函数,它将 return 单词的第一个字符。
主要问题是:
else
{
for(node *ptr = hashtable[alphabetPosition(word[0])]; ptr != NULL; ptr = ptr->next){
hashtable[alphabetPosition(word[0])]->next = new_node;
}
}
因为其他一切都正常。节点已创建,但链表尚未创建。
我很确定这段代码有问题,但我似乎无法理解。如果有人能帮助我(解释如何解决它),那将对我有很大帮助。
谢谢!
主要缺陷是:hashtable[index]
仅且始终指向最后创建的节点。 IE。 hashtable[alphabetPosition(word[0])]->next
始终设置为 new_node
。
for
循环基本上是错误的。该程序只需要将 new_node
指向列表的当前头部(即 hashtable[alphabetPosition(word[0])
然后使 new_node 成为新头部。
我正在做 CS50 的 pset4,它基本上需要您创建 26 个节点(每个节点对应字母表中的每个字母)并在这些节点中创建一个链表以连接字典中的单词。
因此,例如,节点 0 将存储词典中以 A 开头的每个单词,节点 1 将存储词典中以 B 开头的每个单词,等等...
所以,这里是主要的代码:
// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
// for every word, we allocate enough memory for a node, that will carry the word
node *new_node = malloc(sizeof(node));
if(new_node == NULL) { printf("could not allocate memory.\n"); return false; }
strcpy(new_node->word, word);
new_node->next = NULL;
if(!hashtable[alphabetPosition(word[0])]){
hashtable[alphabetPosition(word[0])] = new_node;
}
else
{
for(node *ptr = hashtable[alphabetPosition(word[0])]; ptr != NULL; ptr = ptr->next){
hashtable[alphabetPosition(word[0])]->next = new_node;
}
}
}
alphabetPosition() 基本上是一个函数,它将 return 单词的第一个字符。
主要问题是:
else
{
for(node *ptr = hashtable[alphabetPosition(word[0])]; ptr != NULL; ptr = ptr->next){
hashtable[alphabetPosition(word[0])]->next = new_node;
}
}
因为其他一切都正常。节点已创建,但链表尚未创建。
我很确定这段代码有问题,但我似乎无法理解。如果有人能帮助我(解释如何解决它),那将对我有很大帮助。
谢谢!
主要缺陷是:hashtable[index]
仅且始终指向最后创建的节点。 IE。 hashtable[alphabetPosition(word[0])]->next
始终设置为 new_node
。
for
循环基本上是错误的。该程序只需要将 new_node
指向列表的当前头部(即 hashtable[alphabetPosition(word[0])
然后使 new_node 成为新头部。