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;
    }
}
相关推荐
云烟成雨TD1 天前
Spring AI Alibaba 1.x 系列【6】ReactAgent 同步执行 & 流式执行
java·人工智能·spring
小O的算法实验室1 天前
2026年ASOC,基于深度强化学习的无人机三维复杂环境分层自适应导航规划方法,深度解析+性能实测
算法·无人机·论文复现·智能算法·智能算法改进
于慨1 天前
Lambda 表达式、方法引用(Method Reference)语法
java·前端·servlet
swg3213211 天前
Spring Boot 3.X Oauth2 认证服务与资源服务
java·spring boot·后端
gelald1 天前
SpringBoot - 自动配置原理
java·spring boot·后端
殷紫川1 天前
深入理解 AQS:从架构到实现,解锁 Java 并发编程的核心密钥
java
‎ദ്ദിᵔ.˛.ᵔ₎1 天前
LIST 的相关知识
数据结构·list
一轮弯弯的明月1 天前
贝尔数求集合划分方案总数
java·笔记·蓝桥杯·学习心得
chenjingming6661 天前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
殷紫川1 天前
深入拆解 Java volatile:从内存屏障到无锁编程的实战指南
java