链表 03. 两个链表的交点

题目:给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。  简单

方法一:哈希表  时间复杂度O(N)  空间复杂度O(N)

下面这个哈希表的做法比正常多了个hashB,是因为要处理一些极特殊的情况,即链表中有环的时候,当链表中有环就不建议双指针了,因为判断的东西太多

一些极特殊的结构

 

def getIntersectionNode(headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if not headA or not headB:
            return None
        
        hashA = set()
        pA = headA
        while pA and pA not in hashA:
            hashA.add(pA)
            pA = pA.next
        
        hashB = set()
        pB = headB
        while pB and pB not in hashB:
            if pB in hashA:
                return pB
            hashB.add(pB)
            pB = pB.next
        return None

方法二:双指针  时间复杂度O(N)  空间复杂度O(1)

def getIntersectionNode(headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if not headA or not headB:
            return None
        
        pA = headA
        pB = headB

        while pA != pB:
            pA = pA.next if pA is not None else headB    # 这里犯过一个错误,即next放在了判断之外,没有保证两个指针每次都只前进一步,造成无限循环
            pB = pB.next if pB is not None else headA

        return pA

 

posted @ 2022-07-13 15:11  Liang-ml  阅读(21)  评论(0)    收藏  举报