/** * 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; if (!head->next) return false; const ListNode* next1 = head; const ListNode* next2 = head; do { next1 = next1->next; next2 = next2->next; if (next2) { next2 = next2->next; } } while ((next1 != head) && next1 && next2 && (next1 != next2)); return next1 && next2 && (next1 == next2); } };