【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;
        }
    }


}

记录

总结

相关推荐
SimonKing13 分钟前
AI Assistant被"隐藏"了?别慌,IDEA 2026.3 这波是换了个脑子
java·后端·程序员
我是大猴子18 分钟前
分析sss
开发语言
Resean022319 分钟前
SpringMVC 6+源码分析(九)异常处理
java·spring·springmvc
geats人山人海27 分钟前
现代c++4.1
java·开发语言·c++
布莱克6051 小时前
Swift 字符串详解:从基础用法到性能与最佳实践
服务器·开发语言·ssh·字符串·swift
下一站春风里1 小时前
Spring IoC 控制反转 完整技术笔记
java·spring boot·笔记·spring
挖掘狂人1 小时前
用户连点两次「确认支付」,你的后端凭什么只扣一次钱?
java·后端·面试
codigger2 小时前
用户连点两次「确认支付」,你的后端凭什么只扣一次钱?
java·程序员·支付·java后端
Resean02232 小时前
SpringMVC 6+源码分析(十)数据绑定与类型转换
java·spring·springmvc
lw_zhang11012 小时前
爆肝一个月,Java 从入门到精通39 - 使用Log4j
java·单元测试·log4j