原文地址:https://www.jianshu.com/p/21009b10c42d

时间限制:1秒 空间限制:32768K

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

题目描述

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?

我的代码

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

运行时间:18ms
占用内存:1224k

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄