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

相关推荐
Hero | 柒20 小时前
JAVA反射机制
java·spring·反射
j***630821 小时前
Springboot项目中线程池使用整理
java·spring boot·后端
likuolei21 小时前
Eclipse 创建 Java 接口
java·数据库·eclipse
q***547521 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
a***560621 小时前
Spring Boot接收参数的19种方式
java·spring boot·后端
z***751521 小时前
SpringBoot集成MQTT客户端
java·spring boot·后端
q***697721 小时前
java进阶1——JVM
java·开发语言·jvm
码力码力我爱你21 小时前
C++静态变量依赖关系
java·jvm·c++
q***76661 天前
Java_ElasticSearch(ES)——分布式搜索引擎
java·elasticsearch·搜索引擎
o***59271 天前
解决 IntelliJ IDEA 中 Tomcat 日志乱码问题的详细指南
java·tomcat·intellij-idea