2.2剑指offer的代码题-题2

来源:互联网 发布:中原网络办公 编辑:程序博客网 时间:2024/06/05 10:07

一个链表中包含环,请找出该链表的环的入口结点。

这个比较简单,画图就能解,首先,第一个指针以步进1走,第二个指针一步进二走,当他俩汇聚的时候,A再出发一个步进为1的,当他和第一个指针汇合的时候,就是人口。


调了两遍以为算法有问题,结果是,例子有不是环的。。所以越界了,gg

class Solution {public:    ListNode* EntryNodeOfLoop(ListNode* pHead)    {ListNode* p_firstonestep = pHead;        ListNode* p_firsttwostep = pHead;        ListNode* p_secondonestep = pHead;                if(p_firsttwostep->next == NULL || p_firsttwostep->next->next == NULL)                return NULL;        p_firstonestep = p_firstonestep->next;        p_firsttwostep = p_firsttwostep->next->next;        while(p_firstonestep!= p_firsttwostep)            {            if(p_firsttwostep->next == NULL || p_firsttwostep->next->next == NULL)                return NULL;            p_firstonestep = p_firstonestep->next;        p_firsttwostep = p_firsttwostep->next->next;        }        while(p_firstonestep!= p_secondonestep)            {            p_firstonestep = p_firstonestep->next;            p_secondonestep = p_secondonestep->next;                    }        return p_secondonestep;    }};


原创粉丝点击