现在问题在于它除了第一个以及列表中不存在的值之外的每个值都有效...程序返回垃圾值并崩溃。 (尝试通过递归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 :(得分: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;
}
}