Play and learn 300 000+ tabs online

Monday, May 10, 2010

Y Shaped linkedlist

How will u find the point of intersection of two linked list(Y shape)


Find the length of both the linked list
Find the difference in length(d)
For the longer LL, traverse d node and check the addresses with another LL

void Intersection(struct node* head1, struct node *head2)

{

//find the length of each linked list

int len1=Count(head1), len2=Count(head2);

//find the difference between both the linked list

int diff=(len1>len2)?(len1-len2):len2-len1;

int remainingLength=0;

//Traverse linked list with greater node

//till the remaining length becomes same

//for both the linked list

if(len1-len2>0)

{

remainingLength=len1-diff;

for(int i=1;i<=diff;i++)

head1=head1->next;

}

else

{

remainingLength=len2-diff;

for(int i=1;i<=diff;i++)

head2=head2->next;

}




//Traverse through the emaining length of linked list

//to find the point of intersection

for(int i=0;i

{

//If both the node is same from both the linked list

if(head1==head2)

{

cout<<”\nPoint of intersection is at “<data;

break;

}



//Forward both the pointer when there is no match for

//a particular node

head1=head1->next;

head2=head2->next;

}

}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.