/* Linked List Node struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } }; */ //Function to find intersection point in Y shaped Linked Lists. int length(Node*head) { int i=0; Node*temp=head; while(temp!=NULL) { temp=temp->next; i++; } return i; } int intersectPoint(Node* head1, Node* head2) { int n=length(head1); int m=length(head2); Node*ptr1; Node*ptr2; int d; if(n>m) { d=n-m; ptr1=head1; ptr2=head2; } else{ d=m-n; ptr1=head2; ptr2=head1; } while(d>0){ if(ptr1==NULL){ return -1; } ptr1=ptr1->next; d--; } while(ptr1->next!=NULL && ptr2->next!=NULL) { if(ptr1==ptr2) { return ptr1->data; } ptr1=ptr1->next; ptr2=ptr2->next; } return -1; }
0 Comments