2012-12-15 44 views
0

我編寫了代碼,根據用戶 的選擇從列表中刪除特定的節點,代碼對於特定的值完全正常工作,但如果我使用 幾次調用它意味着我把它叫做2次連續然後我 彼此功能pointer_to_node(index)給出了一個出界錯誤, 也由我來實現記錄這樣的條件下,圓形單鏈表:從列表中刪除一個特定的節點

其實,爲什麼我需要幾個電話,是我必須寫單獨功能 刪除所有節點。我正在嘗試使用此 函數完成該任務,方法是使用一個for循環,直至達到我的Circular Singly Linked列表的大小。 但在這種情況下,它也返回給我一個NULL指針,並給了我超出範圍的 消息(由我在代碼中實現)。我已經包括了我的兩個功能下降 這裏

void remove_from_index(int index){ 
    Node*temptr; 
    temptr = new Node; 
    int tempdata; 

    if (index==1)//means remove from first 
    { 
    temptr = firstptr; 
    tempdata= temptr->data; 
    firstptr = firstptr->nextptr; 
    lastptr->nextptr=firstptr; 
    delete(temptr); 
    } else if(index==size_of_list()) //means last node 
    { 
    temptr = pointer_to_node(index); 
    index--; //get pointer of 2nd last position 
    lastptr = pointer_to_node(index);//setting 2nd last as last postion 
    temptr->nextptr=NULL; 
    temptr=NULL; 
    lastptr->nextptr=firstptr; 
    delete (temptr); 
    } else // any position of node 
    { 
    temptr = pointer_to_node(index); 
    tempdata = temptr->data; 
    index--; // to get address of back 

    Node* temp2ptr; 
    temp2ptr = new Node; 

    temp2ptr = pointer_to_node(index); 

    index = index+2; 

    Node* temp3ptr; 
    temp3ptr = new Node; 

    temp3ptr = pointer_to_node(index); 

    temp2ptr->nextptr = temp3ptr; 

    temptr->nextptr=NULL; 
    delete (temptr); 
    } 
} 


Node* pointer_to_node(int index){ 
    Node*temptr; 
    temptr = new Node; 
    temptr = firstptr; 

    Node*temptr2; 
    temptr2 = new Node; 
    temptr2 = NULL; 
    int count = 1; 

    while (temptr!=temptr2){ 
    if (count==index) 
    { 
     return temptr; 
    } 

    count++; 
    temptr2=firstptr; 
    temptr=temptr->nextptr; 
    } 

    if (index>size_of_list()) 
    { 
    temptr=NULL; 
    cout<< "Can't You think in bounds. Take your NULL Pointer "; 
    return temptr; 
    delete temptr; 
    delete temptr2; 
    } 
} 
+0

你有很多內存泄漏,但總的來說聯動必須工作。如果你已經聲明瞭這個,你可以分享'Node'的內部函數嗎? –

+0

@BorisStrandjev不,我沒有包括析構,,, ....我怎樣才能避免內存泄漏... 實際上,如果我不使用新的應該如何刪除節點呢? –

+0

我會添加一個部分答案指出你有內存泄漏的地方,以及如何解決這個問題。 –

回答

0

您有幾個內存泄漏:

temptr->nextptr=NULL; 
temptr=NULL; // BAD!! BAD!! Remove it otherwise you will not actually free 
lastptr->nextptr=firstptr; 
delete (temptr); 

這裏太(其實你有這樣的代碼的四個地方):

Node* temp2ptr; 
temp2ptr = new Node; // BADD!! Why do you allocate if you are going to reassign? 
temp2ptr = pointer_to_node(index); 

刪除壞道,你會避免內存泄漏。

不過,這不會解決您的問題。

你也有操作回到這裏後:

return temptr; 
delete temptr; 
delete temptr2; 

這些永遠不會被執行。

編輯pointer_to_node功能過於複雜,請與

Node* pointer_to_node(int index) { 
    Node* tempPtr = firstptr; 
    for (int i = 0; i < index; i++) { 
     tempPtr = tempPtr->nextptr; 
    } 
    return tempPtr; 
} 

改變它,看看這是否會解決您的問題。更多的代碼行很少意味着更好的編程技巧,不要人爲地嘗試增加它們的數量。

0

我認爲這裏除了已經詳細記錄的所有內存泄漏和樣式問題之外,另一個可能的問題是您的代碼似乎無法處理列表中只有一件事情的情況。

如果發生這種情況,它會刪除該節點,但將firstptrlastptr指向隨機存儲器。

如果您的size_of_list()函數只是對列表中的節點進行計數,它可能仍會認爲還有非零節點,然後您可能會嘗試刪除或以其他方式訪問另一個節點。