2015-06-02 106 views
0

我想刪除所有與key具有相同idteam的節點,但它會崩潰......我知道它也應該釋放()內存,但無論如何,我認爲這應該工作:S從C上的簡單鏈表中刪除多個節點

//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 
    } 
} 
+0

http://stackoverflow.com/a/30578168/971127 – BLUEPIXY

回答

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

功能是錯誤的。

此代碼段中

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可以等於空,因此下面的語句

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