下面我有一個帶搜索功能的鏈接列表。該功能不僅搜索列表中的元素,還設置之前節點的地址,稍後將用於刪除功能。如果在列表中找到該值,則將返回該節點的地址,否則前一個節點爲空,並且該函數返回null。我收到分段錯誤,我不確定原因。有人可以向我解釋爲什麼?謝謝。搜索鏈接列表
struct IntNodeType {
int value;
IntNodeType * next;
IntNodeType (int v=0, IntNodeType * p=NULL):value(v),next(p)
{
}
};
IntNodeType * Search (IntNodeType * firstNodePtr, int value,
IntNodeType * & prevNode)
{
IntNodeType * cur;
IntNodeType * prev;
cur = firstNodePtr;
prev = prevNode;
while (cur!=NULL)
{
if (cur->value==value)
{
prev -> next = cur;
return cur;
}
cur = cur->next; //update p with the current node's next field
}
prevNode = NULL;
return NULL;
}
你的搜索功能修改列表似乎很奇怪。你確定你的設計? –
'prev - > next = cur;'可能是一個問題。沒有檢查以確保'prev'不是'NULL'。請發佈[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –