【问题标题】:Implementing a Linked List C实现链表 C
【发布时间】:2015-06-03 03:06:45
【问题描述】:

我正在做作业,我想我应该使用链表来存储一些数据。问题是列表没有保留所有节点。

当添加完成并尝试查看节点时,它只显示添加到列表中的最后一个节点。

我将在下面写下相关部分,希望有人能指出问题所在。(我怀疑它一定与malloc有关。函数完成工作后地址被破坏,但不确定。

另外我应该指出,我在添加数据时测试并打印了数据,并且确实表明它们已正确添加到列表中。

/**
 * Adds command name and it's hash onto the linked list
 * returns 1, if successful
 * returns 0, if failed
 */

int addToList(struct CMDList *head, char *pathCommand[], char *hash){

int result = 0;

/** If head was pointing to NULL, list empty, add at the beginning */
if(head->path == NULL){

    head->path = pathCommand[0];
    head->command = pathCommand[1];
    head->hash = hash;
    head->next = NULL;
    result = 1;

}else{

    struct CMDList *current = head;

    /** Find tail of the list */
    while(current->next != NULL){

        current = current->next;
    }
    current->next = (struct CMDList *)malloc(sizeof(struct CMDList));
    if(current->next != NULL){

        current->path = pathCommand[0];
        current->command = pathCommand[1];
        current->hash = hash;
        current->next = NULL;
        result = 1;

    }

}

return result;

}

主程序:

int main(int argc, char *argv[]){

/** CODE DELETED */

/** initialize list for storing cmds from config file */
/** cmdList is the head node that i use to traverse the list */
cmdList = (struct CMDList *)malloc(sizeof(struct CMDList));
if(cmdList != NULL){

    cmdList->path = NULL;
    cmdList->command = NULL;
    cmdList->hash = NULL;
    cmdList->next = NULL;
}else{

    printError("Silent Exit: couldn't initialize list to store commands of config file");
    exit(1);
}


/** CODE DELETED **/

/** add new data to the list */
if(!addToList(cmdList,arrayCommand,sha)){

        printError("Silent Exit: couldn't add to list");
        exit(1);
}

}

【问题讨论】:

标签: c linked-list malloc


【解决方案1】:

在这部分代码中:

if(current->next != NULL){

    current->path = pathCommand[0];
    current->command = pathCommand[1];
    current->hash = hash;
    current->next = NULL;
    result = 1;

}

你必须使用current->next->...而不是current->...,因为你的新元素在current->next,而不是current(事实上,你检查了current->next != NULL)。

由于这个错误,添加的第一个元素很好,但是当您尝试添加第二个元素时,您只是分配了它的空间,然后覆盖了第一个。

【讨论】:

  • 该解决方案确实解决了我遇到的主要问题。我应该多加注意的。但现在还有另一个问题。该列表不断用相同的信息覆盖所有节点,因此最后,所有节点都包含添加到最后一个节点的任何内容。我不知道为什么它被覆盖了,有什么想法吗?
  • @Neo 如果您还有其他问题,请发布另一个问题。这个答案确实解决了你在问题中所说的问题,那你为什么不接受呢?
【解决方案2】:

在这部分代码中你要设置变量 对于当前->下一个

  if(current->next != NULL){

    current->path = pathCommand[0];
    current->command = pathCommand[1];
    current->hash = hash;
    current->next = NULL;
    result = 1;

}

另一种选择是,在执行 malloc 时,您设置一个指向新结构的临时指针, 给出你需要的值,然后设置current->next = temp;

您也可以跳过 while 步骤。你可以有一个名为tail的指针 指向列表的末尾。

然后做一些类似的事情

temp=malloc(...)
temp->path = ...
...
tail->next = temp;
tail = temp;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-03
    • 2021-11-13
    • 1970-01-01
    • 2021-12-23
    • 2015-03-17
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多