• 首先定义两个快慢指针,慢指针一次移动一个位置,快指针一次移动两个位置,如果他们一个指向为空,则没有环,如果他们相等,则有环。
/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */

/**
 * 
 * @param head ListNode类 
 * @return bool布尔型
 */
bool hasCycle(struct ListNode* head ) {
    // write code here快慢指针
    struct ListNode *slow=head;
    struct ListNode *fast=head;
    if(slow==NULL||slow->next==NULL||fast->next->next==NULL){
        return false;
    }
    fast=fast->next->next;
    slow=slow->next;
    while(fast!=NULL){
        if(slow->next==NULL||fast->next==NULL||fast->next->next==NULL){
            return false;
        }
        if(fast!=slow){
            slow=slow->next;
            fast=fast->next->next;
        }else{
            return true;
        }
    }
    
    return false;
}