2014-02-16 108 views
-1

我試圖從雙向鏈表中刪除所有的偶數。雙鏈表刪除C++中的偶數

我已經考慮了案件:

  1. 空單
  2. 甚至在開始數,
  3. 什末數
  4. 偶數列表
  5. 中間偶數不在列表中

我的代碼如下不起作用p roperly:

void DoublyList::deleteEvens() 
{ 

    if (first == NULL) { 
     cerr << "Empty List" << endl; 
    } 


    else { 
     Node *current = first; 
     bool found = false; 
     while (current != NULL && (!found)) { 
      Node *tCurrent = current; 
      if (current->getNextLink() == NULL) { 
       if (current->getData() % 2 == 0) { 
        first = NULL; 
        last = NULL; 
        delete current; 
        current = NULL; 
        count = 0; 
       } 
       else { 
        cerr << "Not in the list" << endl; 
        found = true; 
       } 
      } 

      else if (current == first && current->getData() % 2 == 0) { 
       first = first -> getNextLink(); 
       first->setPreviousLink(NULL); 
       current = current->getNextLink(); 
       delete tCurrent; 
       tCurrent = NULL; 
       -- count; 
      } 
      else if (current == last && current->getData() % 2 == 0) { 
       last = last->getPreviousLink(); 
       last->setNextLink(NULL); 
       delete current; 
       current = NULL; 
       -- count; 
      } 

      else if (current->getData() % 2 == 0) { 
       current->getPreviousLink()->setNextLink(current->getNextLink()); 
       current->getNextLink()->setPreviousLink(current->getPreviousLink()); 
       current = current->getNextLink(); 
       delete tCurrent; 
       tCurrent = NULL; 
      } 
      else { 
       current = current->getNextLink(); 
      } 
     } 
    } 
} 
+0

_'My below will not work properly.'_ too fague question ... –

+0

@πάνταῥεῖ我剛剛開始學習編程,我不知道如何具體,因爲有些代碼可以工作,有些時候不... – Julie

+0

由於這是一個學校項目,你不應該得到代碼。但是,下面是如何解決它 - 將其分解成幾部分。首先編寫一個可以刪除雙向鏈表中的項目的函數。然後測試它。然後編寫一個函數來遍歷列表並查找所有偶數。測試它。然後結合這兩者。不要試圖將其作爲一個巨大的步驟。 –

回答

3

這個問題似乎是你的第一種情況:current->getNextLink() == NULL將評估爲true,在列表中最後一個項目。所以,當你處理最後一個項目時,你會有效地刪除整個列表。

我認爲這是爲了檢測的第一個項目在列表中,將其更改爲:

if (current->getNextLink() == NULL && current->getPreviousLink() == NULL)

,或者將其移出循環外,只是使用的第一個變量。

+0

非常感謝!它現在完全可以工作! :) – Julie

+2

@ProgrammingLearning - 請成爲STL的朋友。節省很多時間 –

+0

@EdHeal感謝您的建議,我剛開始學習,並將探索更多!謝謝您的意見! – Julie