2012-06-23 74 views
0

這是我的remove()函數鏈接列表。怎麼會更好,爲什麼?C鏈接列表刪除功能

void removeData(void *data, struct accList *theList) 
{ 
    if(theList->head == NULL)     //nothing can be deleted 
    return; 
    else if(theList->head == theList->tail)   //there is only one element in the list 
    { 
    free(theList->head); 
    theList->head = theList->tail = NULL; 
    } 
    else if(data == theList->head->data)   //the node to be deleted is the head 
    { 
    struct accListNode *temp = theList->head; 
    free(theList->head); 
    theList->head = temp; 
    theList->head->next = temp->next; 
    } 
    else if(data == theList->tail->data)  //the node to be deleted is the tail 
    { 
    struct accListNode *cur; 
    for(cur = theList->head; cur->next->next != NULL; cur = cur->next); 
    theList->tail = cur; 
    free(cur->next); 
    cur->next = NULL; 
    } 
    else          //the node to be deleted is any other node 
    { 
    struct accListNode *cur; 
    for(cur = theList->head; cur != NULL; cur = cur->next) 
    { 
     if(cur->data == data)  //this is the node we must delete from theList 
     { 
     struct accListNode *temp = cur->next->next; 
     free(cur->next); 
     cur->next = temp; 
     break; 
     } 
    } 
    } 
} 

另外,有人可以給我一個free()函數的詳細解釋。單詞「釋放ptr指向的內存」沒有幫助。

感謝

+0

表格問題「我該如何改進這段代碼?」應該在http://codereview.stackexchange.com上。 –

+0

[你正在尋找代碼評論](http://codereview.stackexchange.com/)。 –

回答

1

而是測試所有不同的特殊情況下,你可以使用指針工作,以列表元素的指針和,因爲你反正遍歷列表,保持看到最後一個元素的軌跡:

void removeData (void *data , struct accList *theList) { 
    struct acclist *last = NULL, **finger = &theList->head; 
    while (*finger != NULL) { 
     if ((*finger)->data == data) 
      *finger = (*finger)->next; 
     else { 
      last = *finger; 
      finger = &((*finger)->next); 
      } 
     } 
    theList->last = last; 
    } 

此代碼從功能不同之處在於它刪除匹配data所有元素,但是你可以很容易地修改它刪除第一元素相匹配data