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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
phltxy7 小时前
C语言操作符详解
java·c语言·算法
aqiu1111118 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye8 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考9 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾9 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研10 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a1879272183111 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_9622974812 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye12 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展