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


}

记录

总结

相关推荐
牛艺翔1 小时前
C++基础
开发语言·c++
键盘会跳舞1 小时前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出
linux-hzh1 小时前
百日算法修炼 · Day 03
java·算法
美味蛋炒饭.1 小时前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发
我星期八休息2 小时前
网络编程—网络层
开发语言·前端·网络·人工智能·智能路由器
不负岁月无痕2 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试
mister_guo2 小时前
Java线程池参数应该如何设置(ThreadPoolExecutor)
java
余额瞒着我当琳2 小时前
C++模板初阶与STL初探
android·java·c++
SomeB1oody2 小时前
【RustyML入门】2.9. MeanShift
开发语言·后端·机器学习·rust·教程
淡海水2 小时前
15-02-YooAsset面试篇-Unity架构设计与源码
java·unity·面试·c#·游戏引擎·yooasset