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


}

记录

总结

相关推荐
AI街潜水的八角1 分钟前
Python电脑屏幕&摄像头录制软件(提供源代码)
开发语言·python
hadage2333 分钟前
--- git 的一些使用 ---
开发语言·git·python
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode
lly2024062 小时前
HTML与CSS:构建网页的基石
开发语言
一只会写代码的猫2 小时前
面向高性能计算与网络服务的C++微内核架构设计与多线程优化实践探索与经验分享
java·开发语言·jvm
萤丰信息3 小时前
智慧园区能源革命:从“耗电黑洞”到零碳样本的蜕变
java·大数据·人工智能·科技·安全·能源·智慧园区
曹牧4 小时前
Eclipse为方法添加注释
java·ide·eclipse
是小胡嘛4 小时前
C++之Any类的模拟实现
linux·开发语言·c++
我叫张小白。4 小时前
Spring Boot拦截器详解:实现统一的JWT认证
java·spring boot·web·jwt·拦截器·interceptor
csbysj20205 小时前
Vue.js 混入:深入理解与最佳实践
开发语言