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


}

记录

总结

相关推荐
天远Date Lab15 分钟前
构建金融级信贷审批系统:Java Spring Boot 集成天远借贷行为验证 API 全指南
java·大数据·spring boot·金融
2401_8414956415 分钟前
【LeetCode刷题】杨辉三角
数据结构·python·算法·leetcode·杨辉三角·时间复杂度·空间复杂度
微爱帮监所写信寄信15 分钟前
微爱帮监狱寄信写信小程序与焦作邮政系统对接技术方案
开发语言·网络协议·小程序·https·php·监狱寄信
lsx20240618 分钟前
适配器模式
开发语言
虾说羊18 分钟前
transferManager为什么在工作中禁止使用 (怎么进行优化 怎么避免多线程的堵塞)
java·服务器·数据库
码农水水18 分钟前
宇树科技Java面试被问:Atomic原子类的实现原理(CAS机制)
java·开发语言
EverestVIP20 分钟前
Qt 信号槽断开连接的几种方式
开发语言·qt
liuc031723 分钟前
JAVA调用deepSeek demo
java·开发语言
9稳29 分钟前
基于PLC的液体自动混合加热控制系统设计
开发语言·网络·数据库·labview·plc
爱吃山竹的大肚肚29 分钟前
Spring Boot 与 Apache POI 实现复杂嵌套结构 Excel 导出
java·spring boot·后端·spring·spring cloud·excel