Loading

[LeetCode] 142. Linked List Cycle Ⅱ(带环单链表之二)

Description

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
给定一个单链表,返回单链表开始成环的地方,如果单链表没有环,返回 null

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
当链表里的某个节点可以通过后续节点的 next 指针再次被访问到时,则称该单链表带环。在本题中,pos 用来指代链表尾节点的 next 指针所指向的节点。注意 pos 并没有被当作参数传入。

Notice that you should not modify the linked list.
注意不能修改原链表。

Examples

Example 1

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

Constraints

  • The number of the nodes in the list is in the range [0, 104].
  • -105 <= Node.val <= 105
  • pos is -1 or a valid index in the linked-list.

Solution

快慢指针找环这部分很简单,这里不再赘述,那么如何找成环的地方呢?其实在原有基础上再加一个操作即可:快指针重新回到 head,一次遍历一个节点;慢指针继续按原有方式遍历。快慢节点再次相遇的地方即为所求。至于为什么这样做可行,有谁能给个证明吗?这触及到我的知识盲区了。代码如下:

class Solution {
    fun detectCycle(head: ListNode?): ListNode? {
        if (head?.next == null) {
            return null
        }
        // 判断是否成环
        var fast = head.next?.next
        var slow = head.next
        while (fast !== slow) {
            fast = fast?.next?.next
            slow = slow?.next
        }
        if (fast == null) {
            return null
        }

        // 找环开始的地方
        fast = head
        while (fast !== slow) {
            fast = fast?.next
            slow = slow?.next
        }
        return fast
    }
}
posted @ 2020-12-02 09:17  Zhongju.copy()  阅读(69)  评论(0编辑  收藏  举报