OneMoreError
OneMoreError

Reputation: 7728

Finding the middle element in a linked list using double pointer method

I wrote the following function which returns the middle element of a linked list, which uses the double pointer method

struct node
{
int data;
struct node *next;
}*start;

void middleelement()
{
struct node *x=start,*y=start;
int n=0;

if(start==NULL)
{
    printf("\nThere are no elments in the list");
}

else
{
    while((x->next)!=NULL)
    {
        x=x->next->next;
        y=y->next;
        n++;
    }

    printf("\nMiddle element is %d",y->data);
}
}

However, whenever I run the functions, the Windows explorer stops working What is the flaw in the code? Is there any better algorithm than this to find the middle element?

Upvotes: 3

Views: 1558

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

If the number of entries is odd, your x will end up being NULL, so when the next loop iteration dreferences it, your program is going to crash. You should modify your condition to account for that:

while(x && x->next) {
    ...
}

Comparing with NULL is optional in C, so you can skip the != NULL to shorten the condition.

Of course passing the start parameter through a global variable is unorthodox, to say the least. It would be much better to pass it as a regular function parameter.

Upvotes: 2

Related Questions