链表中环的入口结点

给一个长度为n链表,若其中包含环,请找出该链表的环的入口结点,否则,返回null。

 

 

 

struct ListNode* EntryNodeOfLoop(struct ListNode* pHead ) {
    // write code here
    if(pHead==NULL|| pHead->next==NULL) return NULL;
    if(pHead->next==pHead) return pHead;
    struct ListNode* f=pHead;
    struct ListNode* s=pHead;
    while(f && s->next && s)
    {
        f=f->next->next;
        s=s->next;      
        if(s==f)
        {
            f=pHead;
            while(1)
            {
                if(f==s) return f;
                f=f->next;
                s=s->next;
            }
        }

    }
   
    return NULL;
}
posted @ 2023-07-14 20:32  歪爱慕外  阅读(15)  评论(0)    收藏  举报