
public int findIntersectingNode(ListNode list1, ListNode list2){
int L1 = 0,L2=0,diff = 0;
ListNode head1 = list1;
ListNode head2 = list2;
while(head1 != null){
L1++;
head1 = head1.getNext();
}
while(head2!=null){
L2++;
head2 = head2.getNext();
}
if(L1<L2){
head1 = list2;
head2 = list1;
diff = L2-L1;
}
else{
head1 = list1;
head2 = list2;
diff = L1-L2;
}
for(int i = 0; i<diff; i++){
head1 = head1.getNext();
}
while(head1!=null && head2!=null){
if(head1 == head2){
return head1.getData();
}
head1 = head1.getNext();
head2 = head2.getNext();
}
return Integer.MAX_VALUE;
}
No comments:
Post a Comment