讨论/《中级算法》 - 相交链表/
《中级算法》 - 相交链表
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode currA = headA;
        ListNode currB = headB;
        int countA = 0;
        int countB = 0;
        while (currA != null) { // 先看两条链表多长
            countA++;
            currA = currA.next;
        }
        while (currB != null) {
            countB++;
            currB = currB.next;
        }
        currA = headA;
        currB = headB;
        for (int i = 0; i < countA - countB; i++) { //让链表长的先走几步,直到剩下一样长
            currA = currA.next;
        }
        for (int i = 0; i < countB - countA; i++) {
            currB = currB.next;
        }
        while (currA != null) { //对比两个链表剩下部分,发现相遇就返回该节点,没有发现就返回null
            if (currA == currB) return currA;
            currA = currA.next;
            currB = currB.next;
        }
        return null;
    }
4
展开全部 12 讨论