第一种双指针,一个每次走一步,一个每次走两步,如果有环,走的快的会超越慢的,然后呢再追上慢的,我们就看是否存在这种追上,如果说没有追上,那就是走的快的最先到达nullptr

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode(int x) : val(x), next(NULL) {}
    7. * };
    8. */
    9. class Solution {
    10. public:
    11. bool hasCycle(ListNode *head) {
    12. if(!head) return false;
    13. auto slow = head, fast = head->next;
    14. while(slow != fast)
    15. {
    16. if(!fast || !fast->next) return false;
    17. slow = slow->next;
    18. fast = fast->next->next;
    19. }
    20. return true;
    21. }
    22. };

    第二种 利用哈希表

    /**
    * 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) {
           if(!head) return false;
           auto pt = head;
           unordered_set<ListNode*> s;
           while(s.find(pt) == s.end())
           {
               s.insert(pt);
               pt = pt->next;
               if(!pt)
                   return false;
           }
           return true;
       }
    };
    

    第二次写题

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