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
xwill end up beingNULL, so when the next loop iteration dreferences it, your program is going to crash. You should modify your condition to account for that:Comparing with
NULLis optional in C, so you can skip the!= NULLto shorten the condition.Of course passing the
startparameter through a global variable is unorthodox, to say the least. It would be much better to pass it as a regular function parameter.