LeetCode OJ--Linked List Cycle **

https://oj.leetcode.com/problems/linked-list-cycle/

判断一个链表是否为循环链表(这个链表可能是 1 2 3 4 然后4指向2)

巧妙的方法:设置两个指针,一个slow,一个fast。每次slow走一个,fast走两个,如果是循环链表,它俩有相等的时候。

 struct ListNode {
     int val;
    ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
};
 
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == NULL)
            return false;

        ListNode *slow = head;
        ListNode *fast = head->next;
        
        while(fast)
        {
            if(slow == fast)
                return true;

            slow = slow->next;
            if(fast->next)
                fast = fast->next->next;
            else
                break;
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/qingcheng/p/3821050.html