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


}

记录

总结

相关推荐
aXin_ya3 分钟前
微服务 第十天 (Redis多级缓存)
java·redis·微服务
逸Y 仙X19 分钟前
文章二十五:ElasticSearch 分页查询
java·大数据·数据库·elasticsearch·搜索引擎·全文检索
今天长肉了吗21 分钟前
风控指标平台实战:大数据量下如何设计分批处理
开发语言·数据库·python
ch.ju31 分钟前
Java programming(The third edition) Chapter Two——Null return value
java·开发语言
1.14(java)1 小时前
Spring事务和事务传播机制
java·数据库·spring
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题】【Java基础篇】第34题:String、StringBuffer和StringBuilder的区别是什么
java·后端·面试
晓庆的故事簿1 小时前
JAVA搭配RabbitMQ使用
java·rabbitmq·java-rabbitmq
折哥的程序人生 · 物流技术专研1 小时前
第3篇:为何要配置环境变量?
java·开发语言·后端·面试
游乐码1 小时前
c#迭代器
开发语言·c#
渔民小镇1 小时前
4 行代码接入 Spring —— ionet 的生态融合之道
java·服务器·分布式·游戏