gpt4 book ai didi

c - 实现链表 C

转载 作者:太空狗 更新时间:2023-10-29 16:11:52 25 4
gpt4 key购买 nike

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

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

我会在下面写相关的部分,希望有人指出问题所在。

另外我应该指出,我测试过,在添加数据时打印数据,它确实表明它们被正确地添加到列表中)。

/**
* 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);
}

}

最佳答案

在这部分代码中:

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)。

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

关于c - 实现链表 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29340470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com