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



我想删除所有具有相同idteam作为key的节点,但它会崩溃…我知道它也应该释放()内存,但无论如何我认为这应该工作: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 );
      }
}

相关内容

  • 没有找到相关文章

最新更新