环的长度

问题: 给出一个单向链表的头指针,如果有环,则返回环的长度,否则返回0。

思路: 使用两个指针,移动速度一快一慢,若快指针先达到尾部,则无环,若快指针追上慢指针,则快指针多走一个环的长度。

java代码:

	int getCircleLength(ListNode head){
        ListNode slow=head;
        if(slow==null||slow.next==null)
            return 0;
        ListNode fast=slow.next.next;
        while(fast!=null&&fast.next!=null){
            if(slow==fast)
                return getLength(slow);
            slow=slow.next;
            fast=fast.next.next;
        }
        return 0;
    }
    
    int getLength(ListNode node){
        int length=1;
        ListNode curr=node;
        while(curr.next!=node){
            length++;
            curr=curr.next;
        }
        return length;
    }
发布了18 篇原创文章 · 获赞 0 · 访问量 665

猜你喜欢

转载自blog.csdn.net/qq_42060170/article/details/104281917
今日推荐