【d54_2】【Java】【力扣】142.环形链表

思路

关于判断是否重复的就hashSet,这种有主动去重性质的类

新建一个hashSet

遍历链表并放进hashSet,

如果不能放,说明这个遍历过,这个就是环的地方

如果最后到遍历到null,说明没环

代码

复制代码
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
         //都加入hashset,listNode是地址引用,节点一定唯一
            //如果有不能添加的,返回当前节点
            HashSet<Object> set = new HashSet<>();
            ListNode cur = head;
            while (cur != null) {
                //如果能添加,continue
                if(!set.add(cur)){
                 return cur;   
                }
                 cur = cur.next;
            }
            //等于null,退出,所以没有环,返回null
            return null;
    }
}

记录

总结

关于判断是否重复的就hashSet,这种有主动去重性质的类

相关推荐
Wang's Blog1 分钟前
Java 接入Redis: 字符串与哈希类型操作命令
java·服务器·redis
智慧物业老杨4 小时前
物业数字化落地思考:真正的转型,是底层数据秩序的重构
java·大数据·人工智能·微服务·系统架构
星空7 小时前
金蝶苍穹build.gradle配置
java·build.gradle
hold?fish:palm8 小时前
34 合并K个升序链表
javascript·算法·链表
步行cgn10 小时前
Spring 基于 XML 的自动装配:byName 详解
java·后端·spring
Navigator_Z10 小时前
LeetCode //C - 1252. Cells with Odd Values in a Matrix
c语言·算法·leetcode
大帅点兵10 小时前
Apache Ant 1.9.9 完整讲解
java
LuTshoes11 小时前
spring ai 实战 手搓 PlaneExecuteAgent
java·人工智能·spring·ai
这料鬼有毒11 小时前
二刷hot100-73.矩阵置零
java
caoerzhong11 小时前
JeeWMS 开源仓库管理系统二次开发与接口对接实战:Java WMS 如何与 ERP、MES 和自动化设备打通
java·开源