SomeSickJoke
SomeSickJoke

Reputation: 31

Searching A Link List In C

I'm trying to search a link list in c, I can get it to match my search string with the first node but not the next any ideas why. Here's my code:

void fnSearchList(struct listnode *ptrH, char strName[50])
{
    struct listnode *ptrTemp = ptrH;
    int nCount = 0;
//  nRet = strcmp(strName, ptrH->arcFirstName);
//  printf("%i", nRet);
    if(!ptrH)
    {
        /* Empty List */
        printf("\n\nEmpty List \n\n");
    }
    else
    {
        while(ptrTemp->ptrNext)
        {
            nRet = strcmp(strName, ptrTemp->arcFirstName);
            if(nRet == 0)
            {
                printf("The value %s has been located\n", ptrTemp->arcFirstName);
                nCount++;
            }
            ptrTemp = ptrTemp->ptrNext;
        }

        if(!nCount)
            printf("\t\tValue not found within the list\n");
        else
            printf("\t\tA total of %d were found\n", nCount);
    }   
    printf("The list totals %d\n", fnTotalList(ptrH));
}

I have marked a few things out as I was testing to see if the strcmp was working which it is.

Upvotes: 0

Views: 145

Answers (3)

ajay
ajay

Reputation: 9680

The condition to check for the while loop should be while(ptrTemp) and not
while(ptrTemp->ptrNext). That is because you already change ptrTemp to point to the next node in the list by doing

ptrTemp = ptrTemp->ptrNext;

So your code skips the last node in the list because lastNode->ptrNext == NULL is true. Also, note that strName parameter of your function fnSearchList is a pointer to char type and not an array of 50 char. You can write it as:

void fnSearchList(struct listnode *ptrH, char *strName) {
    // stuff
}

They are exactly the same.

Upvotes: 1

ryyker
ryyker

Reputation: 23226

Change:

while(ptrTemp->ptrNext)  

To:

while(ptrTemp)

Upvotes: 1

Neil Hampton
Neil Hampton

Reputation: 1883

I think your while loop should be:

while (ptrTemp)

Otherwise it will not look a the last element in the list

Upvotes: 2

Related Questions