删除函数正在使程序崩溃c ++

Remove Function is making the program to crash c++

本文关键字:崩溃 程序 函数 删除      更新时间:2023-10-16
/********************************************
*   Remove the last employee from the list  *
********************************************/
void EmployeeList::Remove() 
{
    newEmployee * nextToEnd = head, 
                * last = head->Next();
    //THIS IS THE PROBLEM
    //no nodes
    if(head == NULL)
        return;
    //remove the only employee in the list
    if(head->Next()== NULL)
    {
        cout << "nttEmployee ID " << head->empID() << " and salary $" 
             << head->ySalary() << " have been removed.n"; 
        head = NULL;
        delete head;
    }
    else
    {  
       // remove the last employee of the list
        while(last->Next() != NULL)
        {
            nextToEnd = last;
            last = last->Next();
        }   
       cout << "nttEmployee ID " << last->empID() << " and salary $" 
            << last->ySalary() << " have been removed.n";  
        delete last;
        nextToEnd->SetNext(NULL);      
    }
}

尝试从空列表中删除时出现问题。我知道如果它是空的,我无法删除,但我不会崩溃程序以显示"员工列表为空。

指定了我认为问题的位置,希望有人可以帮助我解决问题。

您所要做的就是代码中已经显示的内容。请注意它如何使用 cout 将文本输出到控制台。更改您指定"问题"的if语句,即输出消息,然后返回。

但是您的程序崩溃与您标记的内容无关。它因为head->Next()而崩溃。不能对NULL的对象调用方法。这应该在if (head == NULL)检查之后发生。