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

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

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

    借用博客http://www.cnblogs.com/hiddenfox/p/3408931.html的图

    设环的距离为L = (b+c),无环的距离为a,

    假设在时间t相遇,慢指针行驶距离为x,则 1 x t = x,即t=x

    则快指针行驶的距离为2t = 2x,

    则慢指针环上停留点为(x-a)%L,快指针停留点为 (2x-a)%L,由于在t时刻相遇,故(x-a)%L = (2x-a)%L,

    根据同余定理 x%L = 0,

    当快指针相遇后减慢速度为1,快指针从z继续行走a长度停下,则行走的路程为2x+a,在环上的位置为(2x+a-a)%L = 2x%L=2(x%L) = 0,即回到环的起始点,故知道环的起始点

    ListNode* hasCycle(ListNode* head){
        if(head == NULL || head->next == NULL)  return false;
        ListNode* first = head, *second = head;
        while(second!=NULL && second->next!=NULL){
            first = first->next;
            second = second->next->next;
            if(first == second) return first;
        }
        return NULL;
    }
    
    ListNode *detectCycle(ListNode *head){
        ListNode* cycleNode = hasCycle(head);
        if(cycleNode != NULL){
            ListNode* startNode = head;
            while(startNode!=cycleNode){
                cycleNode = cycleNode->next;
                startNode = startNode->next;
            }
        }
        return cycleNode;
    }
  • 相关阅读:
    windows下在yii中使用mongodb
    yii框架便利类CVarDumper使用
    64位虚拟机创建注意事项
    C#中的委托和事件
    Attribute
    NuGet安装及使用教程
    WPF+WEB+WinForm->>表现层共用类
    C#报修系统Ⅱ
    C#带小括号的运算
    工厂模式提供数据源
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3763932.html
Copyright © 2011-2022 走看看