Hello ,
i have written the code for finding the middle element of the list with
0(n) complexity.
please gurus, verify that and let me know if it needs any modifications
and ofcourse i have question to ask
when the no of elements are odd
we can easily find the middle element
suppose
1 2 3 4 5 the middle is 3
but when the no of elements are even
1 2 3 4 5 6
how can we decide the middle element
is there any most widely used way or experts follow.
please let me know
NOTE : in my previous post i have given the insert function you can have a look at it if you need
insert
int find_mid(struct node *nrml)
{
struct node *adv=nrml;
while(adv) {
if(adv->next !=NULL) {
//if(adv->next->next != NULL)
adv = adv->next->next ;
nrml = nrml -> next;
}
else {
printf("with odd :\n");
return nrml->data;
}
}
printf("with even :\n");
return nrml->data;
}
Driver code :
#define ODD 9
#define EVEN 10
int main()
{
struct node *podd=NULL;
struct node *peven=NULL;
int n,d,i=0,ele;
int odd[ODD]={1,2,3,4,5,6,7,8,9};
int even[EVEN]={1,2,3,4,5,6,7,8,9,10};
while(i<ODD)
{
insert(&podd,odd[i++]);
}
i=0;
while(i<EVEN)
{
insert(&peven,even[i++]);
}
display(podd);
ele = find_mid(podd);
printf("\n%d",ele);
printf("\n");
display(peven);
ele = find_mid(peven);
printf("\n%d",ele);
return 0;
}