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?
Thinking of solving problems
Set the list length to n, the length between the head node and the loop node is K. Define two pointers slow and fast,slow each step, fast each walk two steps. When two pointers meet, there are:
- Fast = slow * 2
- Fast-slow = multiples of (n-k)
A multiple of slow (n-k) can be obtained by the above two formulas.
After two pointers meet, the slow pointer is positioned back to the head node, and the fast pointer remains at the node where it meets. At this point they are distance from the loop node is k, and then the step is 1 times the calendar linked list, again meet point is the position of the loop node.
Implementation code
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */ //runtime:16 MsclassSolution { Public: ListNode *detectcycle (ListNode *head) {if(head = = NULL) {returnNULL; } ListNode *slow = head; ListNode *fast = head; while(Fast->next && Fast->next->next) {slow = slow->next; Fast = fast->next->next;if(Fast = = slow) { Break; } }if(Fast->next && Fast->next->next) {slow = head; while(Slow! = fast) {slow = slow->next; Fast = fast->next; }returnSlow }returnNULL; }};
[Leetcode] Linked List Cycle II