LeetCode160.相交链表【最通俗易懂版双指针】

160. 相交链表 - 力扣(LeetCode)

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
    设 
        相交节点为 O,尾节点为 C,len(A->O) = a,len(B->O) = b,len(O->C) = c

    则
        1. len(A->C) = a + c
        2. len(B->C) = b + c
        1式和2式作差得 |a-b| = |lenA - lenB|
    
    故 
        让长链表先走|a-b|步后,再以步长1遍历,A与B将在O相遇
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = 0, lenB = 0;
        ListNode pA = headA, pB = headB;
        
        while (pA != null) {
            lenA ++;
            pA = pA.next;
        }
        while (pB != null) {
            lenB ++;
            pB = pB.next;
        }

        if (lenB > lenA) {
            for (int i = 0; i < lenB - lenA; i ++) {
                headB = headB.next;
            }
        } else {
            for (int i = 0; i < lenA - lenB; i ++) {
                headA = headA.next;
            }
        }

        while (headA != null && headB != null) {
                if (headA == headB) {
                    return headA;
                }
                headA = headA.next;
                headB = headB.next;
        }
        return null;
    }
}
相关推荐
dragoooon343 分钟前
[C++——lesson29.数据结构进阶——「AVL树」]
算法
碧海银沙音频科技研究院7 分钟前
论文写作word插入公式显示灰色解决办法
人工智能·深度学习·算法
Mr_Xuhhh9 分钟前
第一部分:类和对象(中)— 取地址运算符重载
java·开发语言
Selegant12 分钟前
告别传统部署:用 GraalVM Native Image 构建秒级启动的 Java 微服务
java·开发语言·微服务·云原生·架构
__万波__17 分钟前
二十三种设计模式(十三)--模板方法模式
java·设计模式·模板方法模式
动亦定18 分钟前
微服务中如何保证数据一致性?
java·数据库·微服务·架构
长沙京卓21 分钟前
【无人机算法】低空经济下无人机巡检检测识别算法(城市、林业、水利)
算法·无人机
hn小菜鸡22 分钟前
LeetCode 1971.寻找图中是否存在路径
算法·leetcode·职场和发展
王桑.23 分钟前
Spring中IoC的底层原理
java·后端·spring