从链接列表中删除元素(通过递归)

时间:2017-04-15 06:55:00

标签: c++ recursion linked-list

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

1 个答案:

答案 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;
}
}