每日一道Leetcode - 剑指 Offer 52. 两个链表的第一个公共节点

每日一道Leetcode - 剑指 Offer 52. 两个链表的第一个公共节点_第1张图片

# 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:
        """
        两个链表长度分别为L1+C、L2+C, C为公共部分的长度,第一个人走了L1+C步后,回到第二个人起点走L2步;第2个人走了L2+C步后,回到第一个人起点走L1步。 当两个人走的步数都为L1+L2+C时就找到相遇点了
        """
        A = headA
        B = headB
        # 如果有相交,则会返回公共节点
        # 如果不相交,则会均到达None节点
        # 最后一定会结束循环的
        while A!=B:
            A = A.next if A else headB
            B = B.next if B else headA
        return A

你可能感兴趣的:(Leetcode,链表)