Q:

Searching for the last instance of data in a list

I have an assignment to write a function that searches for the last instance of data (integer in this case) in a list. The function breaks with access violation on the line with if statement. 
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;
}

I tried watching what happens with pNode.Here it becomes zero as it should.But then just passes the while statement. What am i doing wrong?

A:

Your while is an infinite loop, change to:
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;
}

