Leetcode 160. Intersecting Linked List
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null){
return null;
}
ListNode pl=headA;
ListNode ps=headB;
int lenA=0;
ListNode curA=headA;
while(curA!=null){
lenA++;
curA=curA.next;
}
int lenB=0;
ListNode curB=headB;
while(curB!=null){
lenB++;
curB=curB.next;
}
int len=lenA-lenB;
if(len<0){
pl=headB;
ps=headA;
len=lenB-lenA;
}
for(int i=0;i<len;i++){
pl=pl.next;
}
while(pl!=ps){
pl=pl.next;
ps=ps.next;
}
return pl;
}