求链表环的长度

思路:
快慢指针第一次相遇后,固定其中一个指针不动,另一个指针以步长为1前进,第二次相遇,它的步数即为环的长度。

public int loopLength(){
        if(this.head==null){
            return 0;
        }
        ListNode fast=this.head;
        ListNode slow=this.head;
        while(fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
            if(slow==fast){
                int count=1;
                slow=slow.next;
                while(slow!=fast){
                    slow=slow.next;
                    count++;
                }
                return count;
            }
        }
        return 0;
    }
发布了67 篇原创文章 · 获赞 12 · 访问量 1516

猜你喜欢

转载自blog.csdn.net/qq_42174669/article/details/102876618