Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 487
OneMoreError Avatar asked May 03 '26 06:05

OneMoreError


1 Answers

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.

like image 123
Sergey Kalinichenko Avatar answered May 04 '26 21:05

Sergey Kalinichenko