Problem: given a first unidirectional pointer linked list, if there is a ring, the length of the loop is returned, otherwise 0.
Ideas: the use of two hands, the moving speed of a fast and slow, fast if the tail pointer reaches the first, no ring, if slow pointer quickly catch up with the pointer, the pointer to walk the length of a fast loop.
java code:
int getCircleLength(ListNode head){
ListNode slow=head;
if(slow==null||slow.next==null)
return 0;
ListNode fast=slow.next.next;
while(fast!=null&&fast.next!=null){
if(slow==fast)
return getLength(slow);
slow=slow.next;
fast=fast.next.next;
}
return 0;
}
int getLength(ListNode node){
int length=1;
ListNode curr=node;
while(curr.next!=node){
length++;
curr=curr.next;
}
return length;
}