劍指offer 鏈表中環的入口結點

題目描述

一個鏈表中包含環,請找出該鏈表的環的入口結點。

思路:常見的方法,雙指針追擊問題,pFast指針每次走兩步,pSlow指針每次走一步,如果pFast能夠與pSlow指針相遇,則一定有環。

關於證明:參考


/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
 
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {
        if(pHead==NULL || pHead->next==NULL)
            return NULL;
 
        ListNode* pSlow=pHead;
        ListNode* pFast=pHead;
        // detect if the linklist is a circle
        while(pFast!=NULL && pFast->next!=NULL){
            pSlow=pSlow->next;
            pFast=pFast->next->next;
            if(pSlow==pFast)
                break;
        }
        // if it is a circle
        if(pFast!=NULL){
            pSlow=pHead;
            while(pSlow!=pFast){
                pSlow=pSlow->next;;
                pFast=pFast->next;
            }
        }
         
        return pFast;
    }
};


LeetCode題目:142. Linked List Cycle II 






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章