Python 相交链表

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

Code:
class Solution:

    headA = [4, 1, 8, 4, 5]
    headB = [5, 0, 1, 8, 4, 5]

    # 哈希表
    # 先将其中一个链表存到哈希表中,此时再遍历另外一个链表查找重复结点
    def getIntersectionNode(self):

        s = set()
        p, q = self.headA, self.headB
        while p:
            s.add(p)
            p = p.next
        while q:
            if q in s:
                return q
            q = q.next
        return None



if __name__ == '__main__':

    s = Solution()
    print(s.getIntersectionNode())
posted @ 2022-03-15 09:42  hnfangh  阅读(86)  评论(0)    收藏  举报