Java算法(5):链表是否有环

龟兔指针:
龟指针slowPtr每次后移1个结点。兔指针fastPtr每次后移2个结点

ListNode findLinkedListLoopBegin(ListNode head){
        if(head==null){
            return null;
        }
        ListNode slowPtr=head;
        ListNode fastPtr=head;
        boolean isLinkedListContainsLoop=false;
        while(slowPtr.next!=null && fastPtr.next.next!=null){
            slowPtr=slowPtr.next;
            fastPtr=fastPtr.next.next;
            if(slowPtr==fastPtr){
                isLinkedListContainsLoop=true;
                break;
            }
        }
        if(isLinkedListContainsLoop){
            slowPtr=head;
            while(slowPtr!=fastPtr){
                slowPtr=slowPtr.next;
                fastPtr=fastPtr.next;
            }
            return slowPtr;
        }
        return null;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容