zoukankan      html  css  js  c++  java
  • [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
        }
    }
    
  • 相关阅读:
    【bzoj4596】[Shoi2016]黑暗前的幻想乡 容斥原理+矩阵树定理
    【bzoj4832】[Lydsy1704月赛]抵制克苏恩 期望dp
    【bzoj3796】Mushroom追妹纸 hash/sa+kmp+二分
    【bzoj3309】DZY Loves Math 莫比乌斯反演+线性筛
    【bzoj2813】 奇妙的Fibonacci数列 线性筛
    面向对象实现简单的学生课程选择
    小案例--面向对象中实现分页
    初识面向对象四(装饰器/反射)
    python小技巧--控制台输出带颜色的文字方法
    初识面向对象三(经典类/多态/鸭子类型/初识封装)
  • 原文地址:https://www.cnblogs.com/zhongju/p/14071928.html
Copyright © 2011-2022 走看看