Given a linked list, if there is a ring, return the starting point of the ring, or return a null pointer if there is no loop.
Unordered_set: A node that has been made, once duplicated, is the starting point. O (n) space
/** 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 | |!head->next)returnNULL; Unordered_set<listnode *>Uset; Uset.insert (head); while(Head-next) { if(Uset.count (Head-next)) returnHeadNext; Uset.insert (Head-next); Head= HeadNext; } returnNULL; }};
Law two: We want to solve in constant space, then we need to analyze one. I have a direct reference to this great God:
Two pointers one step, one walk two steps, assuming in the ring Z meet, then a from X to go, a start from the z, each step, will meet in Y. It's OK to return Y.
Since the two pointer speed knows the A+B = a + B + C + B, then A = = C, so starting with X and Z will meet in Y.
/** 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 | |!head->next)returnNULL; ListNode*L1, *L2, *L3, *L4; L1= head; L2 =Head; while(L1 &&L2) {L1= L1Next; L2= L2Next; if(!L2) Break; L2= L2Next; if(L1 = =L2) Break; } if(!L1 | |!L2)returnNULL; L3=Head; while(1) { if(L3 = =L1)returnL1; L1= L1Next; L3= L3Next; } }};
Leetcode Linked List Cycle II