leetcode 刷题之路 59 Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:

Can you solve it without using extra space?

题目要求,判断一个单链表中是否存在环,若存在返回环的起始节点,否则,返回NULL。

使用快慢指针的方法判断是否存在环,参见文章Linked List Cycle

下面分析怎么寻找环的起始节点。

看下面一张模拟图,fast指针和slow指针相遇点为C,fast走过路程为a+b+c+b,slow走过路程为a+b。

fast指针走过的路程是slow指针走过路程的两倍,所以有等式: a+b+c+b=2(a+b),化简可得a=c;也就是说,起始节点A和相遇节点C距离环的起始节点B距离相同,有了这个条件,我们只要使用两个指针从A,C出发,以相等的速度前进,他们相遇处就是环的起始节点。


AC code:

/**
 * 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||head->next==NULL)
            return NULL;
        ListNode *fast=head,*slow=head;
        while(fast!=NULL&&fast->next!=NULL)
        {
            fast=fast->next->next;
            slow=slow->next;
            if(fast==slow)
                break;
        }
        if(fast==NULL||fast->next==NULL)
            return NULL;
        fast=head;
        while(fast!=slow)
        {
            fast=fast->next;
            slow=slow->next;
        }
        return fast;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值