题目分析
- 当两个链表长度相等时,比较到相同的对象时,即交叉点
- 要满足所有情况下长度都相等,需要互相拼接,才会长度一定相等
Solution
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode curA = headA, curB = headB;
while (curA != curB) { // 都为null时,相等退出
curA = (curA == null) ? headB : curA.next;
curB = (curB == null) ? headA : curB.next;
// 这段代码在两个链表不相交的时候会死循环
// 当next都为null时,又开始重复遍历
// curA = (curA.next == null) ? headB : curA.next;
// curB = (curB.next == null) ? headA : curB.next;
}
return curA;
}
Reference:小码哥MJ