linked-list-cycle-ii

題目描述
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:

Can you solve it without using extra space?

IDEA


借用別人的一個圖來說明。

設置兩個指針,slow每次走一步,fast每次走兩步

X爲鏈表投,Y爲環的起點,Z爲兩個指針相遇位置

a爲從頭到環起點的距離,b+c等於環長l

則有: 2(a+b)=a+b+n(b+c)

=> a=(n-1)b+nc=(n-1)(b+c)+c=(n-1)l+c

即讓一個指針在X,一個指針在Z點(兩個指針速度相同),第一個指針走a距離,等於第二個指針走過c加(n-1)個環長,最終早Y點相遇,即環的起點

CODE

/**
 * 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)
            return NULL;
        ListNode *slow=head,*fast=head;
        while(fast&&fast->next){
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast){
                slow=head;
                while(slow!=fast){
                    slow=slow->next;
                    fast=fast->next;
                }
                return fast;
            }
        }
        return NULL;
    }
};


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