判断两个单链表是否相交,求出相交点
1,定义两个链表PL,PS假设一个长一个短
2,若无相交,返回null;若相交,则先遍历两个链表
3,求两个链表的差值len
4,长链表先走len步,然后,两个链表再一起一步走
//构造环
public static void crateCut(ListNode headA, ListNode headB) {
headA.next = headB.next.next;
}
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;
//求的lenA lenB
while (pL != null) {
lenA++;
pL = pL.next;
}
while (pS != null) {
lenB++;
pS = pS.next;
}
//定义长短链表
pL = headA;
pS = headB;
//差值-》最长的单链表先走len步
int len = lenA - lenB;
if (len < 0) {
pL = headB;
pS = headA;
len = lenB - lenA;
}
//让pL先走len步
while (len > 0) {
pL = pL.next;
len--;
}
//开始一起走 (pL != pS )---->一人一步走
while (pL != pS) {
pS = pS.next;
pL = pL.next;
}
return pL;
}