两个无环链表相交,求第一个交点
思路为:两链表相交为Y形状,采用对齐的思想,将V部分先对齐,设链表1长度为L1,链表2长度为L2,先砍掉|L1-L2|部分,使他们长度相等,即让一个指针指向较长的链表,并向后移动|L1-L2|个位置。然后让两个指针同时往后遍历。最后相遇的位置即第一个交点
public Node findIntersectNode(Node head1,Node head2){
if(head1 == null || head2 == null)
return null;
int length1 = getLength(head1);
int length2 = getLength(head2);
if(length1 > length2){
for(int i=0;i<length1-length2;i++)
head1 = head1.next;
}
if(length1 < length2){
for(int i=0;i<length2-length1;i++)
head2 = head2.next;
}
while(head1!=null && head2!=null){
if(head1 == head2)
return head1;
head1 = head1.next;
head2 = head2.next;
}
return null;
}