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

时间:2015-06-02 16:20:36

标签: c list linked-list nodes erase

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

功能错误。

在此代码段中

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