2つの単独でリンクされたリストの交点が始まるノードを検索するプログラムを書きます。
たとえば、次の2つのリストをリンク:
ノードC1で交差し始めます。
例1:
入力:intersectVal = 8、リスタ= [4,1,8,4,5]、ListBの= [5,0,1,8,4,5]、skipA = 2、SKIPB = 3
出力:ノードとのリファレンス値= 8
入力説明:交差ノードの値が8(二つのリストが交差する場合、これは0であってはならないことに注意してください)です。Aの頭からは、[4,1,8,4,5]として読み取ります。Bの頭部から、[5,0,1,8,4,5]として読み出します。Aにおける交差ノードの前に2つのノードがあります。B.で交差ノードの前に3つのノードが存在します
例2:
入力:intersectVal = 2、リスタ= [0,9,1,2,4]、ListBの= [3,2,4]、skipA = 3、SKIPB = 1つの
出力:値= 2のノードのリファレンス
入力説明:交差したノードの値が2(二つのリストが交差する場合、これは0であってはならないことに注意してください)です。Aの頭からは、[0,9,1,2,4]として読み取ります。Bの先頭から、それは[3,2,4]として読み出します。Aにおける交差ノードの前に3つのノードがあります。1つのノードは、Bの交差ノードの前にあります。
例3:
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: null
Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
func getIntersectionNode(headA, headB *ListNode) *ListNode {
if headA == nil || headB == nil {
return nil
}
lgA := 0
lgB := 0
node := headA
for node != nil {
lgA++
node = node.Next
}
node = headB
for node != nil {
lgB++
node = node.Next
}
longNode := headA
shortNode := headB
diff := lgA - lgB
if lgA < lgB {
longNode = headB
shortNode = headA
diff = lgB - lgA
}
for i := 0; i < diff; i++ {
longNode = longNode.Next
}
for longNode != nil && shortNode != nil {
if longNode == shortNode {
return longNode
}
longNode = longNode.Next
shortNode = shortNode.Next
}
return nil
}