Linked List Cycle

/*
    开始用hash做的,但这明显不是最优的
*/
/**
 * 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) {
        map<ListNode *,int>m;
        while(head){
            if(m[head]) return true;
            m[head] = 1;
            head = head->next;
        }
        return false;
    }
};
/**
 * 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;
        ListNode *p1 = head,*p2 = head->next;
        while(p1&&p2&&p2->next){//{},{1}这种都没有圈
            p1 = p1->next;
            p2 = p2->next->next;
            if(p1 == p2) return true;
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/llei1573/p/4339686.html