美文网首页一起来刷算法题
链表中环的入口结点

链表中环的入口结点

作者: cherryleechen | 来源:发表于2019-05-07 13:12 被阅读0次

    时间限制: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.haomeiwen.com/subject/jrjkoqtx.html