編寫一個程序,找到兩個單鏈表相交的起始節點。
如下面的兩個鏈表:
在節點 c1 開始相交。
示例 1:
輸入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
輸出:Reference of the node with value = 8
輸入解釋:相交節點的值為 8 (注意,如果兩個列表相交則不能為 0)。從各自的表頭開始算起,鏈表 A 為 [4,1,8,4,5],鏈表 B 為 [5,0,1,8,4,5]。在 A 中,相交節點前有 2 個節點;在 B 中,相交節點前有 3 個節點。
示例 2:
輸入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
輸出:Reference of the node with value = 2
輸入解釋:相交節點的值為 2 (注意,如果兩個列表相交則不能為 0)。從各自的表頭開始算起,鏈表 A 為 [0,9,1,2,4],鏈表 B 為 [3,2,4]。在 A 中,相交節點前有 3 個節點;在 B 中,相交節點前有 1 個節點。
示例 3:
輸入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
輸出:null
輸入解釋:從各自的表頭開始算起,鏈表 A 為 [2,6,4],鏈表 B 為 [1,5]。由於這兩個鏈表不相交,所以 intersectVal 必須為 0,而 skipA 和 skipB 可以是任意值。
解釋:這兩個鏈表不相交,因此返回 null。
注意:
如果兩個鏈表沒有交點,返回 null.
在返回結果后,兩個鏈表仍須保持原有的結構。
可假定整個鏈表結構中沒有循環。
程序盡量滿足 O(n) 時間復雜度,且僅用 O(1) 內存。

public static ListNode getIntersectionNode(ListNode headA, ListNode headB) { /*如果有一個為null則返回null*/ if (headA == null || headB == null) { return null; } /*計算2個鏈表的節點個數*/ int countA = 0; int countB = 0; ListNode iterA = headA; ListNode iterB = headB; /*遍歷計算2個鏈表的節點個數*/ while (iterA != null || iterB != null) { if (iterA != null) { countA++; iterA = iterA.next; } if (iterB != null) { countB++; iterB = iterB.next; } } /*計算2個鏈表的差額*/ int margin; ListNode ia = headA; ListNode ib = headB; if (countA > countB) { margin = countA - countB; while (margin > 0) { ia = ia.next; margin--; } } else { margin = countB - countA; while (margin > 0) { ib = ib.next; margin--; } } /*補平差額后一起向后移動,當2個鏈表的節點相等時返回相遇節點*/ while (ia != null && ib != null) { if (ia == ib) { return ia; } ia = ia.next; ib = ib.next; } return null; }
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists