リングチェーンテーブルかどうかを判断する


チェーンテーブルを指定して、リングチェーンテーブルの分析があるかどうかを判断しましょう.2つのポインタの方法で判断することができます.1つの速いポインタ、1つの遅いポインタです.
コードは次のとおりです.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
     
public:
    bool hasCycle(ListNode *head) {
     
        ListNode *fast,*slow;
        fast=slow=head;
        while(fast!=NULL&&fast->next!=NULL){
     
            fast=fast->next->next;
            slow=slow->next;
            if(fast==slow){
     
                return true;
            }
        }
        return false;
    }
};

これはまた進級して、環状の起点を求めて、私達は再びslow=headを設定するだけで、それから更に出会って起点のコードは以下の通りです:
/**
 * 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 *fast,*slow;
        fast=slow=head;
        while(fast!=NULL&&fast->next!=NULL){
     
            fast=fast->next->next;
            slow=slow->next;
            if(fast==slow){
     
                break;
            }
        }
        if(fast!=slow||fast==NULL||fast->next==NULL){
     
            return NULL;
        }
        slow=head;
        while(slow!=fast){
     
            slow=slow->next;
            fast=fast->next;
        }
        return slow;
    }
};