Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

分析:
假設有環,鏈表分兩部分,環外部分和環內部分,環外部分長爲L(是邊的長度,不是點的個數),環內長爲S,設置快慢指針,相遇點在環內距離起始點T處,那麼快指針和慢指針之間有如下關係:L+m*S+T = 2*(L+n*S+T), 化簡得(m-2*n-1)*S+(S-T) = L, 那麼一個指針從鏈表起始點出發,另一個指針從相遇點出發,二者會在環的起始點相遇。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head == NULL||head->next == NULL)
            return NULL;
        ListNode *fast = head, *slow = head;
        while(fast != NULL)
        {
            fast = fast->next;
            if(fast!=NULL)fast = fast->next;
            else
                return NULL;
            slow = slow->next;
            if(fast == slow)
                break;
        }
        if(fast == NULL)
            return NULL;
        ListNode *p = head;
        ListNode *q = fast;
        while(p!=q)
        {
            p = p->next;
            q = q->next;
        }
        return p;
    }
};


發佈了38 篇原創文章 · 獲贊 10 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章