160. Intersection of Two Linked Lists

由于第一次遍历可能因为不等长找不到交点,在遍历完之后需要让链表的尾部等于对方的头节点,直到找到交点跳出循环。

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    if (headA == null || headB == null) return null;

    ListNode nodeA = headA,
             nodeB = headB;
    while (headA != headB) {
        headA = (headA == null) ? nodeB : headA.next;
        headB = (headB == null) ? nodeA : headB.next;
    }
    return headA;
}

results matching ""

    No results matching ""