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;
    }
}
相关推荐
小羊没烦恼!8 小时前
Memory 记忆设计讨论:为什么 Agent Memory 不能只靠向量数据库?
java·开发语言·windows·算法·c#
天远API8 小时前
零信任架构实战:基于天远单人婚姻查询构建自动化联合贷款审计网关
java·人工智能·架构·自动化
九皇叔叔8 小时前
从本地事务到分布式事务
java·分布式·分布式事务·cap·base
黑马程序员毕设8 小时前
基于微信小程序的节目活动报名与管理系统设计与实现
java·开发语言·spring boot·后端·电脑
小坏讲微服务8 小时前
Spring AI 高频面试题20道
java·spring·ai·agent·springai
Bs_MoneyMagnet8 小时前
基于springboot+vue的会议室预约管理系统的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring·毕业设计·计算机毕业设计
sunshine22 girl8 小时前
Java学习 java原理
java·开发语言·学习
ysu_03148 小时前
08-二叉树遍历:四种方式详解
c语言·数据结构·算法·leetcode
咸鱼老弟8 小时前
Speculative Decoding(投机采样):大模型"先猜后验",生成速度翻倍
前端·算法·ai编程
Bs_MoneyMagnet8 小时前
基于springboot+vue的茶铺管理系统的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring·毕业设计·计算机毕业设计