
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
设
相交节点为 O,尾节点为 C,len(A->O) = a,len(B->O) = b,len(O->C) = c
则
1. len(A->C) = a + c
2. len(B->C) = b + c
1式和2式作差得 |a-b| = |lenA - lenB|
故
让长链表先走|a-b|步后,再以步长1遍历,A与B将在O相遇
*/
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA = 0, lenB = 0;
ListNode pA = headA, pB = headB;
while (pA != null) {
lenA ++;
pA = pA.next;
}
while (pB != null) {
lenB ++;
pB = pB.next;
}
if (lenB > lenA) {
for (int i = 0; i < lenB - lenA; i ++) {
headB = headB.next;
}
} else {
for (int i = 0; i < lenA - lenB; i ++) {
headA = headA.next;
}
}
while (headA != null && headB != null) {
if (headA == headB) {
return headA;
}
headA = headA.next;
headB = headB.next;
}
return null;
}
}