title :
Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Code :
With version HashMap
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: BOOLHascycle (ListNode *head) {Std::map<listnode *,BOOL>ifnodeoccured; ListNode*p =Head; while(p) {if(Ifnodeoccured.find (p)! = Ifnodeoccured.end ())return true; Ifnodeoccured.insert (std::p air<listnode *,BOOL> (P,true)); P= p->Next; } return false; }};
Instead of HashMap, use the double-pointer skill version
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: BOOLHascycle (ListNode *head) { if(!head)return false; ListNode*P1 =Head; ListNode*P2 =Head; while(P2->next && p2->next->next) {P2= p2->next->Next; P1= p1->Next; if(P2==P1)return true; } return false; }};
Tips:
Both of these solutions are basic techniques. The second double-pointer technique is more efficient and less space-complex, and seems to be more admired, but the individual always feels hashmap is good and does not rely on skill.
"Linked List Cycle" cpp