链表相交(Java)

本文介绍两种高效解决LeetCode 2490问题的方法,一是利用HashSet存储链表节点快速查找相交点,二是通过巧妙设计遍历策略降低时间复杂度。两种方法的时间复杂度分析和代码实现详尽解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(leetcode 2490)

题目要求

给你两个单链表的头节点 headAheadB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null

方法一

用集合HashSet存放headA节点,先存入,再利用contains()方法判断是否包含。

时间复杂度O(n+m)

代码

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode temp = headA;
        Set basket = new HashSet();
        while(temp != null) {
            basket.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while(temp != null) {
            if(basket.contains(temp)) return temp;
            temp = temp.next;
        }
        return null;
        

方法二

这方法可太妙了。
链表1和链表2的长度分别为m和n,相交长度为l,如何保证时间复杂度降低的情况下,一步找到交点呢?

规律:
如果temp从链表1开始遍历,到头后接入链表2直到交点,那么temp一共经过了(n+m-l)个节点;
而如果temp先遍历2再遍历1,temp同样经过(n+m-l)个节点。

那么此时,两个temp指向同一个节点,即交点,如果没有交点,那么指向空节点null

代码

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode temp1 = headA;
        ListNode temp2 = headB;
        while(temp1 != temp2) {
            temp1 = temp1 == null ? headB : temp1.next;
            temp2 = temp2 == null ? headA : temp2.next;
        }
        return temp1;
    }

这方法可太妙了!!

### 解题思路 解决 LeetCode 相交链表问题的关键在于找到两个单链表相交节点。题目要求使用 Java 实现一个高效且不占用额外空间的算法来完成此任务。 #### 核心思想 1. **长度差法**: - 先分别遍历两个链表,计算它们的长度。 - 然后让较长的链表先走“两者长度之差”的步数,使得两条链表从当前位置到各自的末尾长度一致。 - 接下来同时移动两个指针,当它们指向的节点相同时即为相交点[^4]。 2. **双指针法**: - 利用两个指针分别从链表头开始遍历,并在到达末尾时切换到另一个链表的头部继续遍历。 - 由于两条链表的总路径长度相同(a + (b − c) = b + (a − c)),因此最终两个指针会在某个时刻相遇于相交节点或者都为空[^1]。 ### Java代码实现 以下是一个完整的 Java 实现示例,采用长度差法解决该问题: ```java /** * Definition for singly-linked list. */ public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) { return null; } // 计算两个链表的长度 int lenA = 0, lenB = 0; ListNode tempA = headA, tempB = headB; while (tempA != null) { lenA++; tempA = tempA.next; } while (tempB != null) { lenB++; tempB = tempB.next; } // 重置指针 tempA = headA; tempB = headB; // 让较长的链表先走差值步 if (lenA > lenB) { int diff = lenA - lenB; for (int i = 0; i < diff; i++) { tempA = tempA.next; } } else if (lenB > lenA) { int diff = lenB - lenA; for (int i = 0; i < diff; i++) { tempB = tempB.next; } } // 同时前进,直到找到相交点 while (tempA != null && tempB != null && tempA != tempB) { tempA = tempA.next; tempB = tempB.next; } return tempA; // 返回相交节点或 null } } ``` ### 示例说明 以输入 `headA = [1,9,1,2,4]` 和 `headB = [3,2,4]` 为例,算法会通过调整指针位置确保两条链表同步前进,最终在节点 `2` 处相遇,返回该节点的引用[^2]。 ### 时间与空间复杂度 - **时间复杂度**:O(n + m),其中 n 和 m 分别是链表 A 和 B 的长度。两次遍历分别用于计算长度和寻找点。 - **空间复杂度**:O(1),仅使用了常量级别的额外空间[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值