![]()
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//遍历AB,获得长度
int lenA=0,lenB=0;
ListNode cur = headA;
while(cur!=null)
{
lenA++;
cur = cur.next;
}
cur = headB;
while(cur!=null)
{
lenB++;
cur = cur.next;
}
//获取AB的长度差
int cha = Math.abs(lenA-lenB);
cur = lenA>lenB?headA:headB;
ListNode c = cur==headA?headB:headA;
//让长的表先走cha步
for(int i = 0;i<cha;i++)
cur = cur.next;
//再同时往下走
while(cur!=c && cur!=null && c!=null)
{
cur = cur.next;
c = c.next;
}
return cur==null?null:cur;
}
}