求两个相交链表的交点
public class IntersectingIinkedList {
public static Node getLinkedListLoop(Node head){
if (head == null || head.next == null || head.next.next == null){
return null;
}
Node cur1 = head.next;
Node cur2 = head.next.next;
while (cur1 !=cur2){
if (cur1.next == null || cur2.next.next == null){
return null;
}
cur1 = cur1.next;
cur2 = cur2.next.next;
}
cur2 = head;
while (cur1 !=cur2){
cur1 = cur1.next;
cur2 = cur2.next;
}
return cur1;
}
public static Node getIntersecting(Node head1,Node head2){
int num = 0;
if (head1 == null || head2 == null){
return null;
}
Node cur1 = head1;
Node cur2 = head2;
while (cur1.next != null){
num++;
cur1 = cur1.next;
}
while (cur2.next !=null){
num--;
cur2 = cur2.next;
}
cur1 = num > 0 ? head1 : head2;
cur2 = cur1 == head1 ? head2 : head1;
num = Math.abs(num);
while (num != 0){
num--;
cur1 = cur1.next;
}
while (cur1 != cur2){
cur1 = cur1.next;
cur2 = cur2.next;
}
return cur1;
}
public static Node getLoopIntersecting(Node head1,Node loop1,Node head2,Node loop2){
if (head1 == null || head2 == null){
return null;
}
if (loop1 == loop2){
return getIntersecting(head1,head2);
}else {
Node cur1 = loop1.next;
while (cur1 != loop1){
if (cur1 == loop2){
return loop1;
}
cur1 = cur1.next;
}
}
return null;
}
public static Node intersectingNode(Node head1,Node head2) {
if (head1 == null || head2 == null){
return null;
}
Node loop1 = getLinkedListLoop(head1);
Node loop2 = getLinkedListLoop(head2);
if (loop1 == null && loop2 == null){
return getIntersecting(head1, head2);
}
if (loop1 != null && loop2 != null){
return getLoopIntersecting(head1,loop1,head2,loop2);
}
return null;
}
}