| Title: |
Linked List Cycle II |
| Pass Rate |
30% |
| Difficulty |
Medium |
See the Linked List Cycle I before looking at the upgrade version
Reading the first version will help with the second version, first understand the structure of the ring. Then look at the following picture:
Assuming that the fast and slow pointer is at the intersection of the dividend ring, the starting point of the ring is K, then:
1, the fast hand walk is twice times the slow pointer walk.
2, the slow pointer to meet point when walking path is: x+y
3, the fast pointer to meet the point of walking path is: x+y+z+y=x+2y+z
4, and because 1, all have x+y=x+2y+z
5, Draw: X=z
So we found that the starting point and the coincident point to the beginning of the loop is the same amount of distance. Then we put two pointers from these two places to start the traversal, when again coincident is the loop start point, the specific code is as follows:
1 Public classSolution {2 PublicListNode detectcycle (ListNode head) {3 if(head==NULL)return NULL;4 if(head.next==NULL)return NULL;5 if(head.next.next==NULL)return NULL;6 7ListNode slow=head;8ListNode fast=head;9 Ten while(fast!=NULL&& fast.next!=NULL){ Oneslow=Slow.next; Afast=Fast.next.next; - if(fast==slow) { -slow=head; the while(slow!=fast) { -slow=Slow.next; -fast=Fast.next; - } + returnfast; - } + } A at return NULL; - - } -}
Leetcode------Linked List Cycle II