【问题标题】:Searching for the last instance of data in a list在列表中搜索最后一个数据实例
【发布时间】:2014-07-07 20:22:51
【问题描述】:

我有一个任务要编写一个函数,该函数在列表中搜索数据的最后一个实例(在本例中为整数)。该函数在 if 语句所在的行因访问冲突而中断。

Node* List::SearchLast (int val)
{
    Node* pLast=NULL;
    Node* pNode=pHead;
    while (pHead!=NULL)
    {
        if (pNode->data==val)
            pLast=pNode;
        pNode=pNode->next;
    }
    return pLast;
}

我试着观察 pNode 发生了什么。Here 它应该变为零。但是then 只是通过了 while 语句。我做错了什么?

【问题讨论】:

  • 你想要pNode!=NULL 而不是pHead!=NULL 中的while 吗?没有任何东西可以修改 pHead
  • 更改为while(pNode != Null)
  • @dlf 天哪,谢谢。我真是个白痴。
  • 哈!但至少你知道,对吧? :D 我认为我们都做得更糟。

标签: c++ list function access-violation


【解决方案1】:

你的while是一个无限循环,改成:

Node* List::SearchLast(int val)
{
    Node *pLast = NULL;
    Node *pNode = pHead;
    while (pNode != 0) {
        if (pNode->data == val) pLast = pNode;
        pNode = pNode->next;
    }
    return pLast;
}

【讨论】:

    猜你喜欢
    • 2018-08-14
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多