面试题23:链表中环的入口结点

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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {
        if(!pHead)
            return nullptr;
        ListNode* pMeet = meetingNode(pHead);
        if(!pMeet)
            return nullptr;
        int cnt = 1;
        ListNode* pCnt = pMeet;
        while(pCnt->next != pMeet)
        {
            pCnt = pCnt->next;
            cnt++;
        }//得到环中节点数

        ListNode* p1 = pHead;
        for(int i = 0; i < cnt; ++i)
            p1 = p1->next;
        ListNode* p2 = pHead;
        while(p1 != p2)
        {
            p1 = p1->next;
            p2 = p2->next;
        }
        return p1;
    }

    ListNode* meetingNode(ListNode* pHead)
    {
        if(!pHead)
            return nullptr;
        ListNode* pSlow = pHead->next;
        if(pSlow == nullptr)
            return nullptr;
        ListNode* pFast = pSlow->next;
        while(pFast && pSlow)
        {
            if(pFast == pSlow)
                return pFast;
            pSlow = pSlow->next;
            pFast = pFast->next;
            if(pFast)
                pFast = pFast->next;
        }
        return nullptr;
    }
};

猜你喜欢

转载自blog.csdn.net/chineseqsc/article/details/81272099
今日推荐