思路:
先求出两个链表的长度,求出长度之差k,让较长链表先走k-1步,然后两个链表同时走,最后相遇即为公共节点。
public static ListNode getIntersectionNode(ListNode headA,ListNode headB){
if(headA == null || headB == null) {
return null;
}
//永远指向最长的单链表
ListNode pL = headA;
//永远指向最短的单链表
ListNode pS = headB;
int lenA = 0;
int lenB = 0;
//分别求长度
while (pL != null) {
lenA++;
pL = pL.next;
}
while (pS != null) {
lenB++;
pS = pS.next;
}
pL = headA;
pS = headB;
//求长度的差值
int len = lenA-lenB;
//如果是负数-》pL = headB; pS = headA
if(len < 0) {
pL = headB;
pS = headA;
len = lenB-lenA;
}
//只需要让pL走len步就好了
while (len > 0) {
pL = pL.next;
len--;
}
//走完len步之后 两个同时开始走
//一直走 走到next值相同时 就是交点
while (pL != pS && pL != null) {
pL = pL.next;
pS = pS.next;
}
if(pL == pS && pS != null) {
return pL;
}
return null;
}