gpt4 book ai didi

c - 从C上的简单链表中删除多个节点

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

我想删除所有与键具有相同 idteam 的节点,但它会崩溃......我知道它也应该 free() 内存,但无论如何我认为这应该有效 :S

//defining the struct
struct players {
int idplayer;
int idteam;
struct players *next;
};

struct players *first, *last;

//the function to delete the nodes
void delete(int key){
struct players *post;
struct players *pre;
struct players *auxi;

auxi = first; //initialization of auxi
while(auxi != NULL) //this should run the loop till the end of the list?
{
if(auxi->idteam == key){ //condition to delete
if(auxi == first) first = auxi->next; //erase for the case the node is the first one
else pre->next = post; //erase in the case the node is anywhere else
}
pre = auxi; //saves the current value of auxi
auxi = auxi->next; //increments the position of auxi
post = auxi->next; //saves the position of the next element
}
}

最佳答案

  auxi = auxi->next; //increments the position of auxi
post = auxi->next; //saves the position of the next element

auxi 变为 NULL 时,您将最终执行 post = (NULL)->next;,这是访问冲突(崩溃)。

你真的不需要post,只需要:

if(auxi->idteam == key){ 
if(auxi == first) first = auxi->next;
else pre->next = auxi->next; // We know auxi is not NULL, so this is safe.
}

关于c - 从C上的简单链表中删除多个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30601403/

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