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;
    }
}
相关推荐
一条星星鱼3 小时前
深度学习中的归一化:从BN到LN到底是怎么工作的?
人工智能·深度学习·算法·归一化
zsc_1183 小时前
基于贪心最小化包围盒策略的布阵算法
算法
哈泽尔都3 小时前
运动控制教学——5分钟学会PRM算法!
人工智能·单片机·算法·数学建模·贪心算法·机器人·无人机
聪明的笨猪猪3 小时前
Java Redis “Sentinel(哨兵)与集群”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
222you3 小时前
Mybatis(1)
java·tomcat·mybatis
靠近彗星4 小时前
1.5操作系统引导
java·linux·服务器·操作系统
瑶山4 小时前
社区版Idea怎么创建Spring Boot项目?Selected Java version 17 is not supported. 问题解决
java·spring boot·intellij-idea·创建项目
2301_789015624 小时前
算法与数据结构——排序算法大全
c语言·开发语言·数据结构·c++·算法·排序算法·visual studio
学习编程的Kitty4 小时前
JavaEE初阶——多线程(1)初识线程与创建线程
java·开发语言·java-ee