-
[题目连接](160. 相交链表 - 力扣(LeetCode))
-
解题思路:短链表长度为x,长链表长度为y,想让长链表走
y - x
,然后两个链表同时走,如果相遇直接返回,否则返回空即可。- 注意,题目明确了,两个链表无环
-
代码
class Solution:def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:# 两个有一个是空的 肯定不相交if not headA:return Noneif not headB:return None# 先计算两个链表的长度,假设长的-短的=x# 长的先走x 然后两个一起走 看是否能相遇 能相遇直接返回 否则返回nulllen1 = 0len2 = 0cur = headAwhile cur:len1 += 1cur = cur.nextcur = headBwhile cur:len2 += 1cur = cur.nextif len1 >= len2:step = len1 - len2while step > 0:headA = headA.nextstep -= 1else:step = len2 - len1while step > 0:headB = headB.nextstep -= 1while headA and headB:if headA == headB:return headAheadA = headA.nextheadB = headB.next# 没有相遇return None