The first solution, recording each occurrence of the element
/** 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 *,BOOL>m; while(head) {if(M.count (head))return true; ElseM.insert (Pair<listnode *,BOOL> (Head,true)); Head= head->Next; } return false; }};
The second solution is to change the value of each element that appears to be an impossible value, eg:99999
classSolution { Public: BOOLHascycle (ListNode *head) { if(head = = NULL)return false; ListNode*temp=Head; ListNode*Temp1; intVal =temp->Val; ListNode x (99999); ListNode*x_p = &x; while((temp->next!=x_p) && (temp->next!=NULL))) {Temp1=temp; Temp=temp->Next; Temp1->next =x_p; } if(Temp->next = =x_p)return true; return false; }
Judging the chain list has a ring