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


}

记录

总结

相关推荐
h***04771 小时前
SpringBoot(7)-Swagger
java·spring boot·后端
v***91303 小时前
Spring boot创建时常用的依赖
java·spring boot·后端
xlq223225 小时前
22.多态(上)
开发语言·c++·算法
666HZ6665 小时前
C语言——高精度加法
c语言·开发语言·算法
代码or搬砖6 小时前
MyBatisPlus讲解(二)
java·mybatis
星释6 小时前
Rust 练习册 100:音乐音阶生成器
开发语言·后端·rust
lcu1116 小时前
Java 学习42:抽象
java
Mr.朱鹏6 小时前
RocketMQ安装与部署指南
java·数据库·spring·oracle·maven·rocketmq·seata
雨中飘荡的记忆6 小时前
Spring表达式详解:SpEL从入门到实战
java·spring
Coder-coco6 小时前
个人健康管理|基于springboot+vue+个人健康管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·mysql·论文