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
        }
    }
    
  • 相关阅读:
    echo "http://172.17.26.115:8380/?key=%c8%fd%d0%c7%ca%d6%bb%fa%b1%f9%cf%e4" | mail -s "noresult_monitr error" maolingzhi@jd.com
    python实现的文本编辑器
    PyQt写的浏览单web页面的browser
    中非发展基金
    团队介绍
    微众—国内最大的微信公众服务平台
    微软创投加速器简介
    知方可补不足~SQL为大数据引入分区表
    实时监控Cat之旅~介绍与自定义类型在哪里
    EF架构~Cannot attach the file as database
  • 原文地址:https://www.cnblogs.com/zhongju/p/14071928.html
Copyright © 2011-2022 走看看