讨论/《中级算法》 - 相交链表/
《中级算法》 - 相交链表

双指针注意每次移动步数都要一致

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        tailset = set()
        headpointA = headA
        headpointB = headB
        while(headA != None and headB != None):
            if headA == headB:
                return headB
            if headA.next == None:
                tailset.add(headA)
                if len(tailset) == 2:
                    return None
                headA = headpointB#因为下文置next前进了一步,因此A也必须前进一步
                headB = headB.next#置next其实是进了一步,如果不contiue跳出该段循环,则会导致只有一个节点的例子失败
                continue
            if headB.next == None:
                tailset.add(headB)
                if len(tailset) == 2:
                    return None
                headB = headpointA
                headA = headA.next
                continue
            headA = headA.next
            headB = headB.next
        return None
展开全部 12 讨论