简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM