/*start with a hash, but it's obviously not optimal.*//** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: BOOLHascycle (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) {}}; */classSolution { Public://two pointers, one slow pointer each time plus one, the other fast pointer every time plus two, if there is a lap fast pointer will catch the slow pointer BOOLHascycle (ListNode *head) { if(!head)return false; ListNode*P1 = HEAD,*P2 = head->Next; while(P1&&p2&&p2->next) {//{},{1} None of this is a circle .P1 = p1->Next; P2= p2->next->Next; if(P1 = = p2)return true; } return false; }};
Linked List Cycle