判断给定的两个链表是否相交,若相交返回交点的值
解体思路:Length1 + Length2 = Length2 + Length1, 若两链表相交,则用双指针交替遍历时必然会在交点处发生第一次相遇,此时遍历的节点数<=Length1 + Length2. 所以当指针的遍历节点数大于Length1 + Length2 时,可判断没有交点
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
tempA = headA
tempB = headB
fullTraverseA = 0
fullTraverseB = 0
while(tempA != tempB):
if tempA:
tempA = tempA.next
else:
tempA = headB
fullTraverseA += 1
if fullTraverseA >2 : #完成了3次遍历(2次A + 1次B),可判断没交点
return None
if tempB:
tempB = tempB.next
else:
tempB = headA
fullTraverseB += 1
if fullTraverseB >2:
return None
return tempA