【问题标题】:Linked lists are not created, why? [CS50 pset4]没有创建链接列表,为什么? [CS50 pset4]
【发布时间】:2019-12-10 14:46:11
【问题描述】:

我正在做 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() 基本上是一个返回单词第一个字符的函数。

主要问题是这样的:

else
{
    for(node *ptr = hashtable[alphabetPosition(word[0])]; ptr != NULL; ptr = ptr->next){
        hashtable[alphabetPosition(word[0])]->next = new_node;
    }
}

因为其他一切都在工作。节点已创建,但链表未创建。

我很确定这段代码有问题,但我似乎无法理解。如果有人可以帮助我(解释如何解决它),那对我帮助很大。

谢谢!

【问题讨论】:

  • 您可以使用调试器逐步执行程序,并检查每个步骤是否按预期工作
  • 您在cs50.stackexchange.com上搜索/提问可能会更成功

标签: c linked-list nodes cs50


【解决方案1】:

主要缺陷是:hashtable[index] 始终指向最后创建的节点。 IE。 hashtable[alphabetPosition(word[0])]->next 始终设置为 new_node

for 循环基本上是错误的。程序只需将new_node 指向列表的当前头部(即hashtable[alphabetPosition(word[0]),然后将new_node 设为新头部。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多