s4553711
6/29/2017 - 2:29 PM

141.cpp

/**
 * 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) {
        //return func1(head);
        return func2(head);
    }
    bool func2(ListNode *head) {
        if (head == NULL) return false;
        ListNode *fast = head, *slow = head;
        while(fast && slow && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;
        }
        return false;
    }
    bool func1(ListNode *head) {
        if (head == NULL) return false;
        ListNode* p = head;
        map<ListNode*, bool> hash;
        while(p) {
            if(!hash[p]) {
                hash[p] = true;
                p=p->next;
            } else {
                return true;
            }
        }
        return false;
    }
};