参考:https://www.cnblogs.com/kira2will/p/4109985.html
给定一个链表,要求你判断链表是否存在循环,如果有,给出环的长度,要求算法的时间复杂度是O(N), 空间复杂度是O(1).
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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 }
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public class CheckCircle { public boolean checkCircle(Node head) { Node fast = head; Node slow = head; if (head != null && head.next != null) { while (fast != null) { slow = head.next; fast = head.next.next; if (slow == fast) { return true; } } return false; } return false; } static class Node { int data; Node next; } private int length(Node Node) { boolean flag = checkCircle(Node); int len = 0; if (flag) { while (Node.next!= Node.next.next) { len++; Node=Node.next; } } return len; } }
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public class CheckCircle { public HashMap isCircle(Node head) { Node fast = head; Node slow = head; HashMap<Boolean, Node> map = new HashMap<>(); if (head != null && head.next != null) { while (fast != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { map.put(true, fast); return map; } } } map.put(false, null); return map; } public int length(Node Node) { HashMap map = isCircle(Node); int len = 0; if (map.containsKey(true)) { Node fast = (main.Node) map.get(true); Node slow = fast; do { fast = fast.next.next; slow = slow.next; len++; } while (fast != slow); } return len; } }
前面两个code是错误的,第三个是经过测试正确的