2017-04-15 117 views
0

現在問題在於它對每個值都有效,除了第一個和那些不存在於列表中的程序...程序返回一個垃圾值並崩潰。 (嘗試通過遞歸做的BTW)從鏈接列表中刪除元素(通過遞歸)

bool deleteValue(student *head, int id) { 
    student *curr, *prev; 
    if (head != NULL) 
    { 
     curr = head->next; 
     prev = head; 
     if ((curr->data == id) && (curr->next != NULL)) 
     { 
      prev->next = curr->next; 
      delete(curr); 
      return true; 
     } 
     if (head->data == id) 
     { 
      student *temp = head; 
      head = head->next; 
      delete temp; 
      return true; 
     } 
     if ((curr->data == id) && (curr->next == NULL)) 
     { 
      delete head->next; 
      head->next = NULL; 
      return true; 
     } 
     else 
     { 
      return deleteValue(head->next, id); 
     } 
    } 
    else 
    { 
     return false; 
    } 
}  // function 
    // delete 

cout << "Student has "; 
if (deleteValue(head, 15) == true) { 
    cout << "been "; 
} 
else { 
    cout << "not been "; 
} 
cout << "deleted. "; 
print(head); // function being called 
+0

此外,在進入這並不在崩潰的列表中存在的價值。 「 – abdullah

+0

」簡單地崩潰返回垃圾值「它會崩潰還是會返回垃圾值?它如何做到這一點? – user463035818

+0

@ tobi303它返回一個垃圾值「-1352642642」,那麼它崩潰。 – abdullah

回答

0
bool deleteValue(student *head, int id) { 
student *curr, *prev; 
if (head != NULL) 
{ 
    curr = head->next; 
    prev = head; 
    if (curr!=NULL && curr->data == id && (curr->next != NULL)) //check whether curr is NULL or not NULL 
    { 
     prev->next = curr->next; 
     delete(curr); 
     return true; 
    } 
    if (head->data == id) 
    { 
     student *temp = head; 
     head = head->next; 
     delete temp; 
     return true; 
    } 
    if (curr!=NULL && (curr->data == id) && (curr->next == NULL)) //even here check for NULL 
    { 
     delete head->next; 
     head->next = NULL; 
     return true; 
    } 
    else 
    { 
     return deleteValue(head->next, id); 
    } 
} 
else 
{ 
    return false; 
} 
}