【d44】【Java】【力扣】160.相交链表

思路

先把a链表都放进 一个hashSet集合

再遍历B链表,逐个放进hashSet集合

如果无法放进,说明这个节点就是相交节点

代码

复制代码
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {

    }

   public class ListNode {
       int val;
       ListNode next;
       ListNode(int x) {
           val = x;
           next = null;
       }
   }

    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            //遍历A链表,并都放入hashSet中
            ListNode cur = headA;
            HashSet<ListNode> hashSet = new HashSet<>();
            //每一个都添加到一个hasSet中
            while (cur != null) {
                hashSet.add(cur);
                cur = cur.next;
            }
            //cur指向头部
            //遍历b,如果放不进,说明遇到相交节点
            cur=headB;
            while (cur != null) {
                if(!hashSet.add(cur)){
                    return cur;
                }
            }
            return null;
        }
    }


}

记录

总结

相关推荐
努力成为AK大王几秒前
并发编程的核心挑战、优化方案与核心知识点总结
java·开发语言·数据库
云烟成雨TD4 分钟前
Agent Scope Java 2.x 系列【10】技能(Skill)
java·人工智能·agent
摇滚侠8 分钟前
SpringMVC 入门到实战 DispatcherServlet 源码解读 92-95
java·后端·spring·maven·intellij-idea
AI 编程助手GPT35 分钟前
用 Python 做一个世界杯赛前分析脚本:以巴西 vs 摩洛哥为例
开发语言·网络·人工智能·python·chatgpt
键盘歌唱家36 分钟前
Spring AI 入门分享:它和“直接调 API“到底差在哪
java·人工智能·spring
lihao lihao1 小时前
Linux信号
开发语言·c++·算法
Java患者·1 小时前
《Python 人脸识别入门实践:从人脸检测到人脸比对完整实现》
开发语言·python·opencv·目标检测·计算机视觉·目标跟踪·视觉检测
ceclar1231 小时前
C# 的任务并行库(TPL)
开发语言·c#·.net
宸丶一1 小时前
Day 10:LangGraph - Agent 的图执行引擎
java·windows·python
hikktn1 小时前
Excel 导出 OOM 预防实战:30 万行从堆溢出到 50MB 的演进
java·excel·easyexcel