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


}

记录

总结

相关推荐
圣保罗的大教堂2 小时前
leetcode 3418. 机器人可以获得的最大金币数 中等
leetcode
WiChP2 小时前
【V0.1B5】从零开始的2D游戏引擎开发之路
java·服务器·数据库
cch89182 小时前
汇编与Java:底层与高层的编程对决
java·开发语言·汇编
荒川之神3 小时前
拉链表概念与基本设计
java·开发语言·数据库
cch89183 小时前
汇编与Go:底层到高层的编程差异
java·汇编·golang
chushiyunen3 小时前
python中的@Property和@Setter
java·开发语言·python
禾小西3 小时前
Java中使用正则表达式核心解析
java·python·正则表达式
yoyo_zzm3 小时前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
小樱花的樱花3 小时前
C++ new和delete用法详解
linux·开发语言·c++