链表中环的入口结点

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

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

题目描述

给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

我的代码

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {
        if(pHead==nullptr || pHead->next==nullptr || pHead->next->next==nullptr)
            return nullptr;
        ListNode* fast=pHead->next->next;
        ListNode* slow=pHead->next;
        while(fast!=slow){
            if(fast->next==nullptr || fast->next->next==nullptr)
                return nullptr;
            fast=fast->next->next;
            slow=slow->next;
        }
        fast=pHead;
        while(fast!=slow){
            fast=fast->next;
            slow=slow->next;
        }
        return fast;
    }
};

运行时间:3ms
占用内存:456k

原文地址:https://www.cnblogs.com/cherrychenlee/p/10824825.html