题解 | #链表中环的入口结点#

链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4


/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
        //fast low
        //if have a cycle,fast==slow
        ListNode* slow=hasCycle(pHead);
        if(slow==nullptr)
            return nullptr;//no cycle
        //be sure there is cycle
        ListNode* fast=pHead;
        while(fast!=slow){
            fast=fast->next;
            slow=slow->next;
        }//why
        return slow;
    }
    ListNode* hasCycle(ListNode* head){
        if(head==nullptr) return nullptr;
        ListNode* fast=head;
        ListNode* slow=head;
        while(fast!=nullptr&&fast->next!=nullptr){
            fast=fast->next->next;
            slow=slow->next;
            if(fast==slow)
                return slow;
        }
        return nullptr;
    }
};

why:

公式推导

全部评论

相关推荐

05-03 12:45
西南大学 Java
nsnzkv:你这项目写的内容太多了,说实话都是在给自己挖坑,就算简历过了,后面面试也难受
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务