day14 leetcode-hot100-25(链表4)

141. 环形链表 - 力扣(LeetCode)

1.哈希集合

思路

将节点一个一个加入HashSet,并用contains判断是否存在之前有存储过的节点,如果有便是环,如果没有便不是环。

具体代码
java 复制代码
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        HashSet<ListNode> set = new HashSet<>();
        ListNode p = head;
        while(p!=null){
            if(set.contains(p)){
                return true;
            }
            set.add(p);
            p=p.next;
        }
        return false;
        
    }
}

2.快慢指针

优化空间复杂度为O(1)

思路

一个慢指针每次走1格,一个快指针每次走2格,如果存在环肯定会相遇,如果不存在,最后都为null.

具体代码
java 复制代码
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null){
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while(slow != null && fast != null){
            if(slow==fast){
                return true;
            }
            
            slow=slow.next;
            if(fast.next!=null){
                fast = fast.next.next;
            }
            else{
                return false;
            }
            
        }
        return false;
    }
}
相关推荐
sali-tec33 分钟前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
小明说Java39 分钟前
常见排序算法的实现
数据结构·算法·排序算法
行云流水20191 小时前
编程竞赛算法选择:理解时间复杂度提升解题效率
算法
smj2302_796826523 小时前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
cynicme3 小时前
力扣3531——统计被覆盖的建筑
算法·leetcode
core5124 小时前
深度解析DeepSeek-R1中GRPO强化学习算法
人工智能·算法·机器学习·deepseek·grpo
mit6.8244 小时前
计数if|
算法
a伊雪4 小时前
c++ 引用参数
c++·算法
圣保罗的大教堂5 小时前
leetcode 3531. 统计被覆盖的建筑 中等
leetcode