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

相关推荐
Drifter_yh2 小时前
【黑马点评】Redisson 分布式锁核心原理剖析
java·数据库·redis·分布式·spring·缓存
莫寒清3 小时前
Spring MVC:@RequestParam 注解详解
java·spring·mvc
没有医保李先生4 小时前
字节对齐的总结
java·开发语言
甲枫叶5 小时前
【claude】Claude Code正式引入Git Worktree原生支持:Agent全面实现并行独立工作
java·人工智能·git·python·ai编程
六件套是我5 小时前
无法访问org.springframeword.beans.factory.annotation.Value
java·开发语言·spring boot
LYS_06186 小时前
C++学习(5)(函数 指针 引用)
java·c++·算法
forestsea6 小时前
Spring Cloud Alibaba 2025.1.0.0 正式发布:拥抱 Spring Boot 4.0 与 Java 21+ 的新时代
java·spring boot·后端
IT枫斗者6 小时前
IntelliJ IDEA 2025.3史诗级更新:统一发行版+Spring Boot 4支持,这更新太香了!
java·开发语言·前端·javascript·spring boot·后端·intellij-idea
forestsea6 小时前
Spring Boot 4.0 + JDK 25 + GraalVM:下一代云原生Java应用架构
java·spring boot·云原生