unknown Interview Question
Applications DevelopersCountry: India
Interview Type: In-Person
Node* first=root;
Node* second=root;
Node* prev=null;
while(second.link!=null){
prev=first;
first=first.link;
second=second.link;
if(second.link!=null)
second=second.link;
else{
printf(prev);//printing middle two nodes for even number of nodes present
printf(first);
}
}
printf(first);// printing middle node for odd number of nodes in list
void middlenode(struct node *root)
{
struct node *p,*ptr;
int count1,count2;
count1=0;
count2=0;
root=root->next;
for(ptr=root;ptr;ptr=ptr->next)
{
p=ptr;
count1++;
count2=0;
while(p->next)
{
p=p->next;
count2++;
}
if(count2==count1)
{
printf("MIDDLE NODE IS %d",ptr->info);
break;
}
if(count1>count2)
{
printf("NO MIDDLE NODE IS EXISTING");
break;
}
}
}
This solution is similar to the first example. If you advance a fast pointer twice as often as you advance a slow pointer, you'll find the middle element when the pointer reaches the end. The way I wrote this code assumes that when the length of the list happens to be even, we return length / 2 - 1.
- Chris December 10, 2015