【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,这种有主动去重性质的类

相关推荐
x***38166 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
S***84886 小时前
SpringSecurity踢出指定用户
java
p***s916 小时前
Spring数据库原理 之 DataSource
java·数据库·spring
adobehu6 小时前
麒麟系统安装jdk17
java·jdk
potato_may6 小时前
链式二叉树 —— 用指针构建的树形世界
c语言·数据结构·算法·链表·二叉树
spencer_tseng6 小时前
java.util.IllegalFormatPrecisionException
java·printf
虹科网络安全6 小时前
艾体宝干货 | Redis Java 开发系列#1 从零开始的环境搭建与实践指南
java·数据库·redis
铅笔侠_小龙虾7 小时前
Arthas 命令
java·jvm
java修仙传7 小时前
每日一题,力扣560. 和为 K 的子数组
算法·leetcode
seeyoutlb7 小时前
微服务全局日志处理
java·python·微服务