剑指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 






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