单链表是否带环
public static ListNode HacListCircle(ListNode first){
ListNode fast = first;
ListNode slow = first;
while((fast != null) && (fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return fast;
}
}
return null;
}
若带环,求环的长度
public static int CircleLength (ListNode first){
ListNode fast = first;
ListNode slow = first;
while((fast != null) && (fast.next != null){
fast = fast.next.next;
slow = slow.next;
while (fast == slow) {
int len = 1;
fast = fast.next.next;
slow = slow.next;
while(fast != slow){
len ++;
fast = fast.next.next;
slow = slow.next;
}
return length;
}
}
}
求环的入口点
fast = first;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return slow;