我想删除所有与密钥具有相同idteam的节点,但它将崩溃。。。我知道它也应该释放内存,但无论如何我认为这应该是可行的:

//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.
  }

10-06 05:19
查看更多