我尝试运行我的代码,但是遇到了访问冲突错误。我在谷歌上搜索了一些资源,但我的代码似乎没有任何问题。有人能帮我吗?
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;
}
由于您正在插入到树的末尾,因此可以通过向PlayerListNode添加lastNode成员来优化它;
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
}