codeTop100题(24)160. 相交链表

68 阅读1分钟

1. 题目

160. 相交链表

2. 分析

image.png

a到交点c1需要两步,b需要三步,怎么能让ab同时走到c1呢?

我们假设a走到交点是长度l1,b走到交点是l2,交点到结尾的长度是l3,我们可以发现一个规律:

l1 + l3 + l2 = l2 + l3 + l1

也就是是a、b同时走8步,即a一直走到c3,然后从b开始走;b一直走到c3,然后从a开始走,这样子a 和 b 都是走了8步,刚好走到c1。

3. 代码

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    ListNode nodeA = headA;
    ListNode nodeB = headB;
    while (null != nodeA && null != nodeB) {
        if (nodeA == nodeB) {
            return nodeB;
        }
        nodeB = nodeB.next;
        nodeA = nodeA.next;
        if (null == nodeA) {
            nodeA = headB;
            headB = null;
        }
        if (null == nodeB) {
            nodeB = headA;
            headA = null;
        }
    }
    return null;
}