struct node * FindMiddle(struct node *Head)
{
struct node *ptr1, *ptr2; // we need 2 pointers
ptr1 = ptr2 = Head; // set the pointers to point to the list head initially
int i=0;
while(ptr1->link != NULL) // keep looping until we reach the tail
// (next will be NULL for the last node)
{
if(i == 0)
{
ptr1 = ptr1->link; //increment only the 1st pointer
i=1;
}
else if( i == 1)
{
ptr1 = ptr1->link; //increment both pointers
ptr2 = ptr2->link;
i = 0;
}
}
return ptr2; //now return the ptr2 which points to the middle node
}
No comments:
Post a Comment