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

Deleting multiple nodes from simple linked list on C

我想删除所有与密钥具有相同 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.
  }

函数错误。

在此代码段中

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