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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
学涯乐码堂主1 小时前
有趣的“打擂台算法”
c++·算法·青少年编程·gesp
Tutankaaa2 小时前
知识竞赛题库设计全攻略
人工智能·算法
WolfGang0073212 小时前
代码随想录算法训练营 Day50 | 图论 part08
数据结构·算法·图论
aini_lovee4 小时前
多目标粒子群优化(MOPSO)双适应度函数MATLAB实现
人工智能·算法·matlab
yong99904 小时前
图像融合与拼接:完整MATLAB工具箱
算法·计算机视觉·matlab
春风不语5054 小时前
深入理解主成分分析(PCA)
算法
apollowing4 小时前
启发式算法WebApp实验室:从搜索策略到群体智能的能力进阶(二十二)
算法·启发式算法·web app
晚枫歌F5 小时前
最小堆定时器
数据结构·算法
Lumos_7775 小时前
Linux -- 线程
java·jvm·算法
七颗糖很甜6 小时前
“十五五”气象发展规划:聚焦五大核心任务
大数据·python·算法