[python]代码库
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def getIntersectionNode(headA, headB):
if headA is None or headB is None:
return None
currA = headA
currB = headB
while currA != currB:
currA = headB if currA is None else currA.next
currB = headA if currB is None else currB.next
return currA
# Example usage
# Create the first linked list: 1 -> 2 -> 3 -> 4 -> 5
headA = ListNode(1)
headA.next = ListNode(2)
headA.next.next = ListNode(3)
headA.next.next.next = ListNode(4)
headA.next.next.next.next = ListNode(5)
# Create the second linked list: 6 -> 7 -> 8 -> 4 -> 5
headB = ListNode(6)
headB.next = ListNode(7)
headB.next.next = ListNode(8)
headB.next.next.next = headA.next.next.next # Intersection point
headB.next.next.next.next = headA.next.next.next.next
# Find the intersection point
intersection = getIntersectionNode(headA, headB)
if intersection:
print("Intersection point value:", intersection.val)
else:
print("No intersection point found.")