题解 | #判断链表中是否有环#

判断链表中是否有环

http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

大佬们看看我这个有什么问题,最后一组测试用例无法通过,但最后一组测试用例无法完全输出...

public boolean hasCycle(ListNode head) {
    if (head == null || head.next == null) return false;

    //每次走一步
    ListNode pre = head;
    //每次走两步
    ListNode nex = head.next;

    //nex为空说明到末尾了,pre==nex说明追上了。到末尾了还未追上:没有环。追上了:有环。
    while (pre != nex) {
        if(pre == null || nex.next == null)
            return false;
        pre = pre.next;
        nex = nex.next.next;
    }

    return true;
}
全部评论

相关推荐

仁者伍敌:服务员还要脱颖而出,这是五星级酒店吗
点赞 评论 收藏
分享
06-05 19:46
已编辑
武汉大学 后端
点赞 评论 收藏
分享
废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务