算法题,单链表判断是否有环(leetcode easy),以及判断环入口

发布于 2020-01-31 16:29:35
关注者
0
被浏览
403
1 个回答
  • 面试哥
    面试哥 2020-01-31
    为面试而生,有面试问题,就找面试哥。

    参考回答:

    是否有环:

    while (faster.next != null && faster.next.next != null) {
        faster = faster.next.next;
        slower = slower.next;
        if (faster == slower) {
            return true;
        }
    }
    return false;
    

    判断环入口:

    Node meet = null;
    while (faster.next != null && faster.next.next != null) {
    faster = faster.next.next;
    slower = slower.next;
    if (faster == slower) {
    meet = faster;
    }
    }
    if (meet != null) {
    newSlower = head;
    while (newSlower != slower) {
    newSlower = newSlower.next;
    slower = slower.next;
    }
    return newSlower;
    }
    return null;