2016-02-08 28 views
0

爲什麼我的代碼不會刪除鏈接列表的最後一個元素?我創建了一個當前的指針來橫過我的列表並跳出循環..(接下來是在我的結構中名爲Card_Node的點)。它應該是簡單回答,只是不知道爲什麼它不會刪除最後一個節點列表中的」C++從後退鏈表中移除節點 -

Card_Node *current; 
    current = front; 
    while (current->next->next != NULL){ 
    { 
     current = current-> next; 
    } 
    Card a = current->next->card; 
    return a; 
    delete current->next; 
    current->next = NULL; 
} 
+0

改變了它,但它仍然不會刪除..... \t \t \t Card_Node *電流; \t current = front; \t \t 而(!電流 - >下一步 - >下一= NULL){ \t \t \t 當前\t =電流 - >下; \t} \t \t \t卡a =當前 - >下一個 - >卡; \t \t return a; \t \t delete current-> next; \t \t current-> next = NULL; \t \t } – Lauren

+0

有沒有原因,你不使用'std :: list'? –

回答

1
return current->next->card; // return !! 
delete current->next;   // so this will never be executed 
current->next = NULL; 

更新

正如下面的評論請求進一步的輸入,在這裏是我試圖保持原始原則的更新。

if (front == nullptr) // Special handling of empty list 
{ 
    // Nothing to return - add error handling - throw exception perhaps 
    // or: 
    return ???; // A default card perhaps 
} 
if (front->next == nullptr) // Special handling of list with one element 
{ 
    // Only one element 
    Card a = front->card; 
    delete front; 
    front = nullptr; 
    return a; 
} 

Card_Node *current; 
current = front; 
while (current->next->next != NULL) // Iterate to find last element 
{ 
    current = current-> next; 
} 

// Now current->next is last element, i.e. the one to remove 
Card a = current->next->card; 
delete current->next; 
current->next = NULL; 
return a; 
+0

我現在做了Card a = current-> next-> card;返回一個;刪除current-> next但它仍然不會刪除 – Lauren

1

你檢查兩種不同的方式NULL;這應該只需進行一次如果您想想你的代碼做什麼,當你的列表只有在它(走通這在調試或在紙上)一個元素,那麼你就應該意識到這個問題是什麼。

0

有幾個問題與您的代碼:

  1. 你沒有考慮到如果列表中包含少於兩個節點。
  2. 您在delete之前撥打return,因此跳過delete
  3. 您的while循環中有一個太多的開放大括號。
  4. 當列表中有兩個或更多節點時,您沒有將前一個節點的next指針設置爲NULL。
  5. 如果列表中只有一個節點,則不會將front設置爲NULL。

試試這個:

if (!front) { 
    // no cards in the list, do something... 
    return Card(); 
} 
Card_Node *current = front; 
Card_Node *previous = NULL; 
while (current->next != NULL) { 
    previous = current; 
    current = current->next; 
} 
Card a = current->card; 
delete current; 
if (previous != NULL) { 
    previous->next = NULL; 
} 
if (front == current) { 
    front = NULL; 
}