【LeetCode】142. 环形链表 II

题目描述

LeetCode 题目链接:环形链表 II

题目描述
在这里插入图片描述

题解

  • 快慢指针经典玩法-又称龟兔赛跑方法,Floyd提出的。

版本一

  • 分别循环两次得出结果
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) return null;

        ListNode p = head;
        ListNode fastPoint = p.next;
        
        while ((fastPoint != null && fastPoint.next != null) && p != fastPoint) {
            fastPoint = fastPoint.next.next;
            p = p.next;
        }
        
        if ((p == fastPoint)) {
            p = head;
            fastPoint = fastPoint.next; // 关键
            
            while (p != fastPoint) {
                p = p.next;
                fastPoint = fastPoint.next;
            }
            
            return fastPoint;
        } else
            return null;
    }
}

版本二

  • 与版本一本质无区别
public class Solution {
    public ListNode detectCycle(ListNode p) {
        if (p == null || p.next == null) return null;

        ListNode turtle = p;
        ListNode rabbit = p;

        while (rabbit != null && rabbit.next != null) {
            turtle = turtle.next;
            rabbit = rabbit.next.next;
            if (turtle == rabbit) {
                turtle = p;
                while (turtle != rabbit ){
                    turtle = turtle.next;
                    rabbit = rabbit.next;
                }
                return turtle;
            }
        }
        return null;
    }
}

版本三

  • set 集合判重
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) return null;
        
        ListNode point = head;

        Set<ListNode> markedNodes = new HashSet<ListNode>();

        for (point = head; point != null && markedNodes.add(point); point = point.next);

        return point;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值