160. 相交链表

  1. [题目连接](160. 相交链表 - 力扣(LeetCode))

  2. 解题思路:短链表长度为x,长链表长度为y,想让长链表走y - x,然后两个链表同时走,如果相遇直接返回,否则返回空即可。

    • 注意,题目明确了,两个链表无环
  3. 代码

    class Solution:
        def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
            # 两个有一个是空的  肯定不相交
            if not headA:
                return None
            if not headB:
                return None
            
            # 先计算两个链表的长度,假设长的-短的=x
            # 长的先走x 然后两个一起走  看是否能相遇  能相遇直接返回  否则返回null
            len1 = 0
            len2 = 0
            cur = headA
            while cur:
                len1 += 1
                cur = cur.next
            cur = headB
            while cur:
                len2 += 1
                cur = cur.next
            if len1 >= len2:
                step = len1 - len2
                while step > 0:
                    headA = headA.next
                    step -= 1
            else:
                step = len2 - len1
                while step > 0:
                    headB = headB.next
                    step -= 1
            while headA and headB:
                if headA == headB:
                    return headA
                headA = headA.next
                headB = headB.next
            # 没有相遇
            return None
    
posted @ 2025-01-09 09:35  ouyangxx  阅读(17)  评论(0)    收藏  举报