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;
    }
}
相关推荐
Stecurry_302 分钟前
Springboot整合SpringMVC --从0到1
java·spring boot·后端
Serene_Dream2 分钟前
NIO 的底层机理
java·jvm·nio·mmap
鱼跃鹰飞2 分钟前
Leetcode会员尊享面试100题:1086:前五科的均分
算法·leetcode·职场和发展
༾冬瓜大侠༿3 分钟前
C++string
c语言·开发语言·c++·算法
Lethehong4 分钟前
探索高效工作流的秘密:GLM-4.7 与 Dify 平台深度集成实践
大数据·人工智能·算法
Yeats_Liao6 分钟前
微调决策树:何时使用Prompt Engineering,何时选择Fine-tuning?
前端·人工智能·深度学习·算法·决策树·机器学习·prompt
skywalker_116 分钟前
多线程&JUC
java·开发语言·jvm·线程池
sin_hielo7 分钟前
leetcode 3010
数据结构·算法·leetcode
黎雁·泠崖7 分钟前
Java基础核心能力总结:从语法到API的完整知识体系
java·开发语言
sheji34169 分钟前
【开题答辩全过程】以 基于协同过滤算法电影个性化推荐系统设计与实现为例,包含答辩的问题和答案
算法