1. 程式人生 > >【探索-中級演算法】相交連結串列

【探索-中級演算法】相交連結串列

在這裡插入圖片描述

注意題目要求的時間與空間複雜度。

只要保持交點之前移動的距離相等即可。即在遍歷 A、B 的時候要同時從 a1 和 b2 開始,這樣才能保證同時遍歷到相交的 c1。

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    if (headA == null || headB == null) return null;
    ListNode tmpA = headA;
    ListNode tmpB = headB;
    int aCounts = 0;
    while (tmpA!=null) {
        ++aCounts;
        tmpA = tmpA.next;
    }
    int bCounts = 0;
    while (tmpB!=null) {
        ++bCounts;
        tmpB = tmpB.next;
    }
    tmpA = headA;
    tmpB = headB;
    // 如果 headA 的節點比 headB 的多
    if (aCounts>bCounts) {
    	// 移動 headA 的指標到合適的位置
        for (int i = 0; i < aCounts-bCounts; i++) {
            tmpA = tmpA.next;
        }
    } else {
        for (int i = 0; i < bCounts-aCounts; i++) {
            tmpB = tmpB.next;
        }
    }
    while (tmpA != null && tmpB != null) {
        if (tmpA==tmpB) return tmpA;
        else {
            tmpA = tmpA.next;
            tmpB = tmpB.next;
        }
    }
    return null;
}