剑指offer---面试题23 链表中环的入口节点

题目描述

给一个链表,若其中包含环(代码中要考虑单链表这种异常),请找出该链表的环的入口结点,否则,输出null。

ListNode* MeetingNode(ListNode* pHead)
{
    if(pHead == nullptr)
        return nullptr;

    ListNode* pSlow = pHead->m_pNext;
    if(pSlow == nullptr)    //考虑单链表这种异常
        return nullptr;

    ListNode* pFast = pSlow->m_pNext;
    while(pFast != nullptr && pSlow != nullptr)  //考虑单链表这种异常
    {
        if(pFast == pSlow)
            return pFast;


       // pSlow = pSlow->next;


       // pFast = pFast->next;
       // if(pFast != nullptr)
        //    pFast = pFast->next;
        pFast = pFast->next;
        if(pFast!=nullptr&&pFast==pSlow)
            return pFast;
        
        pFast=pFast->next;
        pSlow=pSlow->next;t;
    }

    return nullptr;
}

ListNode* EntryNodeOfLoop(ListNode* pHead)
{
    ListNode* meetingNode = MeetingNode(pHead);
    if(meetingNode == nullptr)
        return nullptr;

    // 得到环中结点的数目,之后不用再考虑但链表的情况,因为若是但链表则上面已返回nullptr
    int nodesInLoop = 1;       //这个初值是1,因为相遇节点必在环内,nodesInLoop 至少是1,开始时候我把它初值赋0于是错了

    ListNode* pNode1 = meetingNode;
    while(pNode1->m_pNext != meetingNode)
    {
        pNode1 = pNode1->m_pNext;
        ++nodesInLoop;
    }

    // 先移动pNode1,次数为环中结点的数目
    pNode1 = pHead;
    for(int i = 0; i < nodesInLoop; ++i)
        pNode1 = pNode1->m_pNext;

    // 再移动pNode1和pNode2
    ListNode* pNode2 = pHead;
    while(pNode1 != pNode2)
    {
        pNode1 = pNode1->m_pNext;
        pNode2 = pNode2->m_pNext;
    }

    return pNode1;
}

猜你喜欢

转载自blog.csdn.net/qq_34793133/article/details/81008418
今日推荐