【问题标题】:Deleting multiple nodes from simple linked list on C从C上的简单链表中删除多个节点
【发布时间】:2023-03-15 13:26:01
【问题描述】:
我想删除所有与 key 具有相同 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
}
}
【问题讨论】:
标签:
c
list
linked-list
nodes
erase
【解决方案1】:
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.
}
【解决方案2】:
函数错误。
在这段代码中sn-p
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
auxi可以等于NULL所以下一条语句
post = auxi->next; //saves the position of the next element
导致未定义的行为。
但这不是唯一的错误。您还必须正确设置节点last。
你必须释放已删除的节点。
函数可以如下所示
void delete( int key )
{
struct players *prev = NULL;
struct players *auxi = first;;
while ( auxi != NULL )
{
if ( auxi->idteam == key )
{
struct players *tmp = auxi;
if ( auxi == first ) first = auxi->next;
else prev->next = auxi->next;
if ( auxi == last ) last = prev;
auxi = auxi->next;
free( tmp );
}
}