title :
Given a linked list, return the node where the cycle begins. If There is no cycle, return null .
Follow up:
Can you solve it without using extra space?
Code :
Using version HashMap
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*detectcycle (ListNode *head) {Std::map<listnode *,BOOL>ifnodeoccured; ListNode*p =Head; while(p) {if(Ifnodeoccured.find (p)! = Ifnodeoccured.end ())returnp; Ifnodeoccured.insert (std::p air<listnode *,BOOL> (P,true)); P= p->Next; } returnNULL; }};
No HashMap version (O (1) space complexity)
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*detectcycle (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) {P1=Head; while(P1! =p2) {P1= p1->Next; P2= p2->Next; } returnP1; } } return false; }};
Tips:
Individuals still like HashMap solution, because more unified, but when the amount of data is very large, the opening up HashMap occupies a lot of resources.
The second solution refers to the following two logs:
Http://www.cnblogs.com/hiddenfox/p/3408931.html
http://blog.csdn.net/cs_guoxiaozhu/article/details/14209743
only the case with ring is discussed here:
Speed pointer skill; slow = = fast, then the distance is twice times the walking distance, let's slow down from the beginning, quickly from the meeting point, but each time to take a step, then meet again the place is the starting point.
This is a special skill, whether it is the head to meet the point how long, are satisfied. Still like the practice of HashMap.
"Linked List Cycle II" cpp