zoukankan      html  css  js  c++  java
  • 142. Linked List Cycle II

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

    Note: Do not modify the linked list.

    Follow up:
    Can you solve it without using extra space?

    假设head到环的位置距离为a,俩pointer相遇距离环起始位置为b

    2(a + b + mCycle) = a + b + nCycle;

    =>a+b = (n-m)Cycle

    a = (n-m)Cycle - b;

    所以一开始俩个pointer相遇位置与head一同往下走,再次相遇的位置即为cycle起始点。

    public ListNode DetectCycle(ListNode head) {
             if(head == null) return null;
             var slow = head;
             var fast = head;
             while(fast!= null && fast.next != null)
             {
                 slow = slow.next;
                 fast = fast.next.next;
                 if(slow == fast) break;
             }
             if(fast== null || fast.next == null) return null;
             slow = head;
             while(slow != fast)
             {
                 slow = slow.next;
                 fast = fast.next;
             }
             return slow;
         }
        

    扩展问题

    http://www.cnblogs.com/hiddenfox/p/3408931.html

    在网上搜集了一下这个问题相关的一些问题,思路开阔了不少,总结如下:

    1. 环的长度是多少?

    2. 如何找到环中第一个节点(即Linked List Cycle II)?

    3. 如何将有环的链表变成单链表(解除环)?

    4. 如何判断两个单链表是否有交点?如何找到第一个相交的节点?

  • 相关阅读:
    3.5.3 数据排序;重复数值、缺失值处理
    3.5.1 pandas基础
    3.3 numpy
    数据准备和特征工程
    2.4函数
    2.3语句与控制流
    2.2数据结构与序列
    2.1Python基础知识
    五、MySQL安装
    四、Hadoop HA 集群搭建
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5867876.html
Copyright © 2011-2022 走看看