单链表环的检测

参考: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 }
View Code

 

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;
    }
}
View Code

 

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;
    }
}
View Code

 前面两个code是错误的,第三个是经过测试正确的

posted @ 2018-10-09 18:01  ZECDLLG  阅读(140)  评论(0编辑  收藏  举报