user1369975
user1369975

Reputation: 420

Wrong output in searching a linked list

I created a linked list and then used the following search function to get the position of the data field,but it returns the value as the last element of the linked list.I am unable to guess why

int search(struct node *curr,int d,int i)
{
if (!(curr-1))
    return(0);
if (curr->data == d)
    return i;

else
{
    i++;
    search(curr->link,d,i);
}
 }

I used the following statement to control it from main:

m=search(first,data,i) //here first is the pointer to first element to first element and data is element to search

Upvotes: 1

Views: 78

Answers (2)

md5
md5

Reputation: 23699

if (!(curr-1))

Why -1?

else
{
    i++;
    search(curr->link,d,i);
}

You have forgotten the return statement. Otherwise, the return value is undefined. Then, your recursive search function might look like:

int search(struct node *curr, int d, int i)
{
    if (curr == NULL)
        return 0; /* If 1 <= i <= n */
    else if (curr->data == d)
        return i;
    else
        return search(curr->link, d, i + 1); 
}

Upvotes: 3

Michał Fita
Michał Fita

Reputation: 1319

Why recursion? You learn bad habits.

int search(struct node* curr, int d, int i)
{
    if (NULL == curr)
    {
       return 0;
    }
    i = 1;
    while(curr->data != d)
    {
        if (NULL != curr->link)
        {
            curr = curr->link;
            ++i;
        }
        else
        {
            return 0;
        }
    }
    return i;
}

Upvotes: 1

Related Questions