@kamakshi this code will work for every value except when your list has only one node.for that you will have to add check : p=head; q=head; if(p->link == NULL) printf("The middle element is %d",p->data); else { if(q->link->link!=NULL) {
p=p->link; q=q->link->link; } printf("The middle element is %d",p->data);
Given an integer n, write a function that returns count of trailing zeroes in n!. Examples: Input: n = 5 Output: 1 Factorial of 5 is 20 which has one trailing 0. Input: n = 20 Output: 4 Factorial of 20 is 2432902008176640000 which has 4 trailing zeroes. Input: n = 100 Output: 24
p=head;
ReplyDeleteq=head;
if(q->next->next!=NULL)
{
p=p->next;
q=q->next->next;
}
printf("The middle element is %d",p->data);
There is a problem in the above code.It does not work if there is a single node,or there are odd no of nodes.
ReplyDeleteit should be like this:
int middle(struct node *head)
{
p=head;
q=head;
if(head->next==NULL)
return (p->data);
else
while(q->next->next!=NULL)
{
p=p->next;
if(q->next!=NULL)
q=q->next->next;
else
return (p->data);
}
return(p->data);
}
@kamakshi this code will work for every value except when your list has only one node.for that you will have to add check :
ReplyDeletep=head;
q=head;
if(p->link == NULL)
printf("The middle element is %d",p->data);
else
{
if(q->link->link!=NULL)
{
p=p->link;
q=q->link->link;
}
printf("The middle element is %d",p->data);