LeetCode 刷题【142. 环形链表 II】

142. 环形链表 II

自己做

解:三指针

java 复制代码
/**
 * 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) {
        if(head == null || head.next == null)           //必定无环
            return null;
        
        ListNode p = head;
        ListNode q = head.next;
        ListNode r = head.next;

        while(r != null){
            r = r.next;                                 //快指针
            if(r != null)
                r = r.next;

            q = q.next;                                 //慢指针

            if(q == p)                                  //遇到入口
                return p;

            if(r == q)                                  //快指针追上了慢指针(转了一圈)
                p = p.next;

        }   

        //无环
        return null;     
    }
}

看题解

java 复制代码
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode slow = head, fast = head;
        while (fast != null) {
            slow = slow.next;
            if (fast.next != null) {
                fast = fast.next.next;
            } else {
                return null;
            }
            if (fast == slow) {
                ListNode ptr = head;
                while (ptr != slow) {
                    ptr = ptr.next;
                    slow = slow.next;
                }
                return ptr;
            }
        }
        return null;
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/linked-list-cycle-ii/solutions/441131/huan-xing-lian-biao-ii-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
2301_763472461 分钟前
C++20概念(Concepts)入门指南
开发语言·c++·算法
abluckyboy1 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
园小异1 小时前
2026年技术面试完全指南:从算法到系统设计的实战突破
算法·面试·职场和发展
m0_706653231 小时前
分布式系统安全通信
开发语言·c++·算法
天天爱吃肉82182 小时前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
alphaTao2 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习2 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
颜酱2 小时前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
不知名XL3 小时前
day50 单调栈
数据结构·算法·leetcode
@––––––3 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划