封面

LeetCode 题解 · 相交链表

笔记日期
# LeetCode
# Python
# 双指针

这里的“相交”是两条链从某个节点起共用一段内存。两条链都写着 8、9,只要它们是分别创建的节点,就没有相交。反过来,只要碰到同一个节点,后面一定也是同一条路。

让 A 为 1 → 共享的 8 → 9,B 为 2 → 3 → 共享的 8 → 9。A 比 B 少一个独有节点。先走完自己的链,再从对方开头走,每个人都补走了另一段独有前缀,最终会同时抵达共享的 8。没有共享部分时,两个人会同时走到空。

class Solution:
    def getIntersectionNode(self, headA, headB):
        a, b = headA, headB
        while a is not b:
            a = a.next if a is not None else headB
            b = b.next if b is not None else headA
        return a

题目给的是无环链表,不需要裁剪或改动它们。开头就相交时循环一次也不用跑。两条链的长度为 m、n,时间 O(m+n),空间 O(1)。

LeetCode 第 160 题

返回 LeetCode 题单 →