链表-求链表环的长度

//求链表环的长度
public class Node{
    public int value;
    public Node next;
    public Node(int data){
        this.value=data;
    }
}
public int findLoopLength(Node head){
    Node fast=head;
    Node slow=head;
    boolean loopExist=false;
    int len;
    if(head==null){
        return 0;
    }
    while(fast.next!=null&&fast.next.next!=null){
        slow=slow.next;
        fast=fast.next.next;
        if(slow==fast){
            loopExist=true;
            break;
        }
    }
    if(loopExist){
        fast=fast.next;
        while(slow!=fast){
            fast=fast.next;
            len++
        }
        return len;
    }
    //链表没有环
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42146769/article/details/88430572