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

相关推荐
qqacj7 分钟前
Spring Security 官网文档学习
java·学习·spring
Rsun0455118 分钟前
10、Java 桥接模式从入门到实战
java·开发语言·桥接模式
金銀銅鐵20 分钟前
[Java] 从 class 文件看 cglib 对 MethodInterceptor 的处理 (下)
java·后端
lee_curry22 分钟前
Java中关于“锁”的那些事
java·线程·并发·juc
pearlthriving28 分钟前
c++当中的泛型思想以及c++11部分新特性
java·开发语言·c++
疯狂打码的少年36 分钟前
有序线性表删除一个元素:顺序存储 vs 单链表,平均要移动多少个元素?
数据结构·算法·链表
y = xⁿ1 小时前
20天速通LeetCode day07:前缀和
数据结构·算法·leetcode
梦魇星虹1 小时前
idea Cannot find declaration to go to
java·ide·intellij-idea
小雅痞1 小时前
[Java][Leetcode hard] 42. 接雨水
java·开发语言·leetcode
xfcoding1 小时前
关于代码注释的思考
java