参考:https://www.cnblogs.com/kira2will/p/4109985.html
给定一个链表,要求你判断链表是否存在循环,如果有,给出环的长度,要求算法的时间复杂度是O(N), 空间复杂度是O(1).
1 public class CheckCircle { 2 public boolean checkCircle(Node head){ 3 Node fast=head; 4 Node slow=head; 5 if(head!=null && head.next!=null){ 6 while (fast!=null){ 7 slow=head.next; 8 fast=head.next.next; 9 if(slow==fast){ 10 int len= length(slow); 11 return true; 12 } 13 } 14 return false; 15 } 16 return false; 17 } 18 static class Node { 19 int data; 20 Node next; 21 } 22 private int length(Node Node){ 23 int len=1; 24 Node slow=Node.next; 25 Node fast=Node.next.next; 26 while(slow!=fast){ 27 slow=Node.next; 28 fast=Node.next.next; 29 len++; 30 } 31 return len; 32 } 33 }