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


}

记录

总结

相关推荐
quikai19816 分钟前
python练习第六组
java·前端·python
222you6 分钟前
线程的常用方法
java·开发语言
云栖梦泽10 分钟前
易语言界面美化与组件扩展
开发语言
catchadmin11 分钟前
PHP 值对象实战指南:避免原始类型偏执
android·开发语言·php
Trouville0120 分钟前
Python中encode和decode的用法详解
开发语言·python
是梦终空22 分钟前
JAVA毕业设计259—基于Java+Springboot+vue3工单管理系统的设计与实现(源代码+数据库+开题报告)
java·spring boot·vue·毕业设计·课程设计·工单管理系统·源代码
JS_GGbond23 分钟前
JavaScript事件循环:餐厅里的“宏任务”与“微任务”
开发语言·javascript·ecmascript
用户21903265273525 分钟前
Spring Boot 集成 Redis 实现看门狗 Lua 脚本分布式锁
java·后端
zybsjn28 分钟前
ShardingSphere 启动报错 “Unknown table ‘keywords‘ in information_schema“ 完整解决方案
java
月明长歌34 分钟前
【码道初阶】【LeetCode 102】二叉树层序遍历:如何利用队列实现“一层一层切蛋糕”?
java·数据结构·算法·leetcode·职场和发展·队列