gpt4 book ai didi

c - 链接列表的访问冲突错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:34:03 25 4
gpt4 key购买 nike

我尝试运行我的代码,但是,我遇到了访问冲突错误。我用谷歌搜索了一些资源,但我的代码似乎没有任何问题。有人可以帮帮我吗?

void addToEnd(PlayerListNode *newNode){

if (newNode == NULL) {
printf("ERROR");
exit(1);

}
printf("\n Inserting %d ... \n", newNode->player);
PlayerListNode *current = listHead;
while (current -> next != NULL)
{
current = current->next;
}
current->next = newNode;
}

错误发生在while循环运行时。

最佳答案

这个解决方案是基于我的猜测

void addToEnd(PlayerListNode *newNode){

if (newNode == NULL) {
printf("ERROR");
exit(1);

}

if(!listHead){
printf("\n First node %d inserted... \n", newNode->player);
listHead=newNode;
return;
}

printf("\n Inserting %d ... \n", newNode->player);
PlayerListNode *current = listHead;
while (current -> next != NULL)
{
current = current->next;
}
current->next = newNode;
}

因为你是插入到树的末尾,所以可以通过将 lastNode 成员添加到 PlayerListNode 来优化它;

void addToEnd(PlayerListNode *newNode){

if (newNode == NULL) {
printf("ERROR");
exit(1);

}

if(!listHead){
printf("\n First node %d inserted... \n", newNode->player);
listHead=newNode;
}
listHead->LastNode->next = newNode;
listHead->LastNode=newNode;
listHead->LastNode->next = NULL; //unsure it is NULL in case of newNode is listHead
}

关于c - 链接列表的访问冲突错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33980203/

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