/**
* Definition for singlylinked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
use faster and lower runner solution. (2 pointers)
the faster one move 2 steps, and slower one move only one step.
if there's a circle, the faster one will finally "catch" the slower one.
(the distance between these 2 pointers will decrease one every time.)
if there's no circle, the faster runner will reach the end of linked list. (NULL)
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL  head > next == NULL)
return false;
ListNode *fast = head;
ListNode *slow = head;
while(fast > next && fast > next > next){
fast = fast > next > next;
slow = slow > next;
if(fast == slow)
return true;
}
return false;
}
};
My faster and slower runner solution


I came up with a similar solution but simplified a bit more:
class Solution { public: bool hasCycle(ListNode *head) { ListNode* slow = head; ListNode* fast = head; while(fast && fast>next) { slow = slow>next; fast = fast>next>next; if(slow == fast) { return true; } } return false; } };
There's no need to check for
if(head == NULL  head > next == NULL) return false;
This information is contained in while(fast && fast>next)