2012-12-12 223 views
1

我正在從迭代刪除功能,從鏈表中刪除節點,我認爲代碼應該工作正常,它遍歷列表,找到所需的節點,指向頭到下一個節點,並刪除當前,但是當我試運行它,我得到無限循環,可以請你幫我查明錯誤,這裏是功能:從鏈接列表中刪除節點

typedef struct E_Type * List; 
struct E_Type 
{ 
    int data; 
    struct E_Type* next; 
}; 

功能:

bool erase(List & l, int data){ 
List head = l; 
if (l != 0){ 
    for(List current = head; current; current = current->next){ 
    if (current->data == data) 
     head = current->next; 
     delete current; 
     return true; 
    } 
    } 
return false; 
} 

測試程序:

int main() 
{ 
    List l = 0; 
    cout << boolalpha << l->data << "went well? "<< (insert(l,73)) << endl; 
    cout << boolalpha << l->data << "went well? "<< (insert(l,24)) << endl; 
    print(cout,l); 
    cout << boolalpha << "Is deleted 24? "<<(erase(l,24)) << endl;  
    cout << boolalpha << "Is deleted 35? "<<(erase(l,35)) << endl; 
    print(cout,l); 
    cout << endl; 
    return 0; 
} 

插入:

bool insert(List & l, int data) 
{ 

    List current = l; 
    while(current != 0) { 
     if (current->data == data) 
     return false; 
     current = current->next; 
    } 

    if (l == 0 || l->data > data){ 
     List new_list = new E_Type; 
     new_list->data = data; 
     new_list->next = l; 
     l = new_list; 
    return true; 
    } 

    else if(l->data < data){ 
    insert(l->next, data); 
    return true; 
    } 

} 
+0

什麼是List類型? –

+0

對不起,我忘了粘貼typedef,現在它在那裏 – EmilDo

+0

我在'erase'中看到第二個'if'語句後面沒有''''。這看起來是無意的;你有多個語句縮進後面。嘗試將這些語句括在大括號中。 (仍然有錯誤,但看起來像是一個大問題,看起來像是無條件地刪除了第一個條目。) – cHao

回答

2

正如Andreas Brinck已經指出的那樣,您還需要更新'上一個'鏈接。不過,你不需要爲這個專門的變量,只要用一個指針的指針:

bool erase(List & l, int data){ 
    List *it = &l; 
    while (*it) { 
    if ((*it)->data == data) { 
     List next = (*it)->next; 
     delete *it; 
     *it = next; 
     return true; 
    } 
    it = &(*it)->next; 
    } 
    return false; 
} 

這也需要謹慎的處理所有的「特殊情況」,比如從空的列表中刪除,刪除列表中的第一個元素或刪除列表中的最後一個元素。

+0

非常感謝,poiner解決方案非常好,現在我現在如何在其他功能中輕鬆地引用prev節點。 – EmilDo

+0

優雅的解決方案,+1 –

0

我們可能需要看到您的插入方法爲好。

難道

current == current->next 

如果是的話,可能會導致無限循環。

+0

我已經粘貼了它 – EmilDo

3

您需要在跟蹤前一個節點,以及用於循環,這樣做:

prev->next = current->next; 
delete current; 

您還需要處理的就是刪除元素是第一要素的情況下列表,在這種情況下,你需要設置ll->next

bool erase(List & l, int data){ 
if (l != 0){ 
    for(List current = head, prev = 0; current; prev = current, current = current->next){ 
    if (current->data == data) 
    { 
     if (prev) 
     { 
      prev->next = current->next; 
     } 
     else 
     { 
      l = current->next; 
     } 
     delete current; 
     return true; 

    } 
    } 
return false; 
} 

你的第一擦除可能創建一個循環鏈表現在。

+0

如何跟蹤此for循環中的前一個節點,我也是想到了這個解決方案,但不知道如何在這裏實現prev節點。 – EmilDo

+0

看起來更像是在刪除之前刪除所有條目。 (因爲它實際上並沒有刪除它們,但是它正在泄漏內存。) – cHao

+0

是的..我怎麼會錯過這個,我應該關閉循環中的if語句 – EmilDo