所以我試圖在C++中創建一個Template Link List類。一切都很完美,包括remove()和search(),除了當我調用兩個方法的值不在LinkList中時。理想情況下,我希望方法在發現該值不在列表中後返回,但是,我覺得這些方法仍然繼續,並嘗試刪除或進一步搜索值,因爲當我運行可執行文件時, 「Segementation Fault(核心轉儲)」錯誤。如果在空列表上調用方法,程序將輸出正確的錯誤。鏈接列表:當列表中的值不在列表中時,remove()和search()方法無法正常工作
該列表單獨與頭部鏈接,並且使用「智能節點」(即,包含它們自己的方法來補充匹配的類方法的節點而不是不包含方法並且需要類方法的「啞節點」創建指向節點的臨時指針並遍歷列表)。
這裏是search()和remove()的實現。當然,我可以提供,如果需要更多的代碼:
//==========================REMOVE================================
template <class T>
void TLinkedList<T> :: remove(T value){
if(!head){ //if there is no head
std::cerr << "Error: List is Empty" << std::endl; // The list is empty
return;
}
if(head->data == value){
listSize--; //decremenets listSize since a node is removed
node * temp = head;
head = head->next;
delete head;
return;
}
else{
if(head->remove(value)){ //If something was removed as a result of the node's remove()
listSize--;
return; //decrement listSize since something was removed
}
else{ //else if nothing removed
std::cerr << "Error : Value not in list" << std::endl;
return;
}
}
}
template <class T>
bool TLinkedList<T> :: node :: remove(T value){ //returns a bool. If something was removed, returns true. If nothing was removed, returns false
if(next-> data == value){
node * temp = next;
next = next->next;
delete temp;
return true; //something removed
}
if(!next){
return false;
}
else{
return next -> remove(value);
}
}
//==============SEARCH===================
template <class T>
T TLinkedList<T> :: search(T value){
if(!head){
std::cerr << "Error: List is empty" << std::endl;
return 0;
}
if(head->data == value){ //If head's data is the value searched for
return head->data; //return head's data
}
else{
return head->search(value);
}
}
template <class T>
T TLinkedList<T> :: node :: search(T value){
if(data == value){
return data;
}
if(!next){
std::cerr << "Error: Value not in list" << std::endl;
return 0;
}
else{
return next->search(value);
}
}
所以,對於一個main(),如:
int main(){
TLinkedList ll;
ll.prepend(5); //adds 5 to list
ll.remove(4); // value of 4 not in list
// OR ll.search(4);
return 0;
}
的CERR不會發生和「分段錯誤(核心轉儲)'給出了錯誤。
任何幫助,非常感謝。謝謝!
編輯:另外,在search()方法中,您可能會注意到我返回0;當發生錯誤時。該實現是在遇到錯誤時試圖停止該方法;理想情況下,我寧願搜索不返回任何東西,如果遇到錯誤
如果找不到元素,您應該讓您的搜索函數返回包含正在搜索的元素的節點或返回'nullptr'。然後你的刪除將簡單地調用搜索,然後刪除元素 – smac89