在列表中搜索数据的最后一个实例

Searching for the last instance of data in a list

本文关键字:最后一个 实例 数据 搜索 列表      更新时间:2023-10-16

我有一个赋值来编写一个函数,该函数在列表中搜索数据的最后一个实例(在本例中为整数)。该函数在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发生了什么。这里它变成了0。然后传递while语句。我做错了什么?

您的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;
}