public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode pa = headA;
int al = 0;
while(pa != null){
al++;
pa = pa.next;
}
ListNode pb = headB;
int bl = 0;
while(pb != null){
bl++;
pb = pb.next;
}
int step = 0;
if(al > bl){
step = al -bl;
int s = 0;
while(headA != null && s < step){
headA = headA.next;
s++;
}
while (headA != headB){
headA = headA.next;
headB = headB.next;
}
return headA;
}else{
step = bl -al;
int s = 0;
while(headB != null && s < step){
headB = headB.next;
s++;
}
while (headA != headB){
headA = headA.next;
headB = headB.next;
}
return headA;
}
}
}
将长度比较长的链表指针提前赶到短链表的头结点位置,然后2个指针以同样步伐一步一步往下走,直到找到相交节点或返回空值