2011-05-20 129 views
2

我想檢查一個實體是否存在於給定的鏈表中。這是我的代碼:C++鏈表簡單問題

bool LinkedList::existByID(int ID) 
{ 
//create node to search through the list 
Node * helpNode; 

//start it at the top of the list 
helpNode = head;  

if (head == NULL) 
{ 
    return false; 
} 


//while the item has not yet been found 


while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNode->data != NULL)) 
    { 

    if (helpNode->data->indicatedEntity->getID() == ID) 
    { 
     //return true - the data exists 
     return true; 
    } 

    else 
     //if the data has not been found, move on 
     helpNode=helpNode->next; 
    } 

//if the data has not been found and the end of the 
//list has been reached, return false - the item does 
//not exist 
return false; 
} 

從我標示爲「問題行」的路線,部分if語句

(helpNode->data != NULL) 

我得到錯誤CXX0017(符號「」未找到)和錯誤CXX0030(不能評估表達式)。

如果在鏈表中沒有實體,換句話說,如果頭爲空,則此代碼有效。

節點構造是這樣的:

LinkedList::Node::Node() 
{ 
next=NULL; 
data=NULL; 
} 

我也用線試了一下:

(helpNode != NULL) 

和節點構造

LinkedList::Node::Node(){} 

所有組合返回相同錯誤。有什麼建議麼?

+0

我想這是作業嗎?如果是這樣,請將其標記爲這樣(以便答案可以讓您向正確的方向推進,而不是告訴您該做什麼)。如果沒有,使用'std :: list'。 – sbi 2011-05-20 07:23:54

+0

請發佈確切的錯誤消息。我假設它的運行時錯誤... – Mayank 2011-05-20 07:25:53

+2

我已經看到至少有一個問題 - 條件必須改寫爲 (helpNode-> data!= NULL)&&(helpNode-> data-> notedEntity-> getID()! = ID) 在解引用它之前,您必須檢查指針是否爲空。 – Muxecoid 2011-05-20 07:26:03

回答

2

首先,我建議用你的代碼修復一些東西。

在你的循環您檢查helpNodedata成員之前測試,看是否helpNode實際上是有效的。想象一下,你在最後一個節點 - 在下一個節點結束時 - 現在在頂部檢查什麼?

helpNode=helpNode->next; 

其次,一旦你檢查helpNode,下次你應該檢查data檢查data屬性,如果有什麼dataNULL之前是有效的?

現在想想你的循環檢查什麼,它檢查getID() != ID,然而在循環內部,你正在測試IDgetID() == ID?那有意義嗎?

我建議您在循環中檢查下一個節點和data是否存在,然後在循環中檢查ID是否匹配,如果爲true,則返回。

+0

謝謝!你是對的,我做這件事的方式並不合理。 – BIU 2011-05-20 07:45:37

0

井行,如果數據爲NULL

while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNode->data != NULL))

可能是一個問題,因爲這樣你會試圖訪問空值> indicatedEntity

如果進一步indicatedEntity爲NULL,那麼你試圖訪問空值>的getID()

您可以將其改寫爲

while (helpNode->data != NULL && helpNode->data->indicatedEntity != NULL && helpNode->data->indicatedEntity->getID() != ID)

這看起來不錯,但它確實確保您的指針在嘗試訪問它們之前不爲空。

+0

您在重寫的表達式中忘了一個重要檢查。 – Nim 2011-05-20 07:30:01

+0

你是指helpNode? – Vusak 2011-05-23 01:53:57

+0

@Nim在它們原始代碼的上下文中,以及我的語句「well the line ...」,你可以看到他們已經在while循環之前檢查了helpNode的狀態。 – Vusak 2011-05-23 07:04:40