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

相关推荐
TimberWill21 分钟前
SpringBoot整合Srping Security实现权限控制
java·spring boot·后端
期末考复习中,蓝桥杯都没时间学了1 小时前
力扣刷题19
算法·leetcode·职场和发展
Renhao-Wan1 小时前
Java 算法实践(四):链表核心题型
java·数据结构·算法·链表
踩坑记录2 小时前
递归回溯本质
leetcode
_codemonster2 小时前
JavaWeb开发系列(六)JSP基础
java·开发语言
万邦科技Lafite3 小时前
淘宝店铺所有商品API接口实战指南
java·数据库·mysql
好学且牛逼的马3 小时前
【Hot100|25-LeetCode 142. 环形链表 II - 完整解法详解】
算法·leetcode·链表
jjjxxxhhh1233 小时前
【加密】-AES与对称加密
java·服务器·网络
临水逸3 小时前
飞牛fnos 2025 漏洞Java跨域URL浏览器
java·开发语言·安全·web安全
yaoxin5211233 小时前
324. Java Stream API - 实现 Collector 接口:自定义你的流式收集器
java·windows·python