【问题标题】:Remove Function is making the program to crash c++删除函数正在使程序崩溃 c++
【发布时间】:2016-03-08 19:42:28
【问题描述】:
/********************************************
*   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 << "\n\t\tEmployee 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 << "\n\t\tEmployee ID " << last->empID() << " and salary $" 
            << last->ySalary() << " have been removed.\n";  

        delete last;
        nextToEnd->SetNext(NULL);      
    }
}

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

我指定了我认为问题所在,希望有人能帮我解决。

【问题讨论】:

  • 如果head 为NULL,你希望head-&gt;Next() 做什么?

标签: c++ class linked-list


【解决方案1】:

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

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

【讨论】:

  • //这是问题 //没有节点 if(head == NULL) { cout
  • 我无法理解第二个解释。你的意思是我不能使用 IF(HEAD->NEXT() == NULL)?那我应该使用什么条件?
  • @DestinyAlyshaCampos 首先,转大写锁定。关于我解释的第二部分,您说您的程序崩溃了,我正在解释原因。这对你来说是个问题:last = head-&gt;Next();,我已经解释了原因。
  • @DestinyAlyshaCampos ,Jonathon 的意思是你这样做:last = head-&gt;Next();,然后再测试使用if(head == NULL) 这样做是安全的。解决办法很明显:改变顺序。
  • 感谢 JonathonOgden 和 user4581301 帮助我修复错误! :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
相关资源
最近更新 更多