力扣 142. 环形链表 II floyd判环

https://leetcode-cn.com/problems/linked-list-cycle-ii/
在这里插入图片描述

思路: f l o y d floyd floyd判环,一个 s l o w slow slow指针,一个 f a s t fast fast指针,前者一次一步,后者一次两步。如果后者遇到了 N U L L NULL NULL的情况,说明链表无环,否则两者一定会在某个位置相遇。那么我们思考一下怎么求入环节点,先看下图:
在这里插入图片描述
下文中的距离表示的是两点之间的边数。我们假设入环节点为 x x x,两个指针在 y y y相遇,从 h e a d head head x x x的距离为 l e n len len,从 x x x y y y的距离为 d i s dis dis,假设环的长度为 L L L s l o w slow slow走过的距离为 d i s _ s l o w dis\_slow dis_slow f a s t fast fast走过的距离为 d i s _ f a s t dis\_fast dis_fast,那么易得: d i s _ s l o w = l e n + d i s dis\_slow=len+dis dis_slow=len+dis d i s _ f a s t = l e n + d i s + k ∗ L dis\_fast=len+dis+k*L dis_fast=len+dis+kL其中 K K K是一个正整数。我们又知道 d i s _ f a s t = 2 ∗ d i s _ s l o w dis\_fast=2*dis\_slow dis_fast=2dis_slow,将上式化简可得: l e n = k ∗ L − d i s len=k*L-dis len=kLdis,也即 d i s + l e n = k ∗ L dis+len=k*L dis+len=kL。那么此时我们再令一个新的指针 c u r = h e a d cur=head cur=head,然后同时移动 c u r 、 s l o w cur、slow curslow,二者相等时的节点就是入环节点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head==NULL)
            return NULL;
        ListNode *slow=head;
        ListNode *fast=head;
        while(1){
            if(fast->next==NULL)
                return NULL;
            else
                fast=fast->next;
            if(fast->next==NULL)
                return NULL;
            else
                fast=fast->next;
            slow=slow->next;
            if(slow==fast)
                break;
        }
        slow=head;
        while(slow!=fast)
            slow=slow->next,fast=fast->next;
        return slow;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值