zoukankan      html  css  js  c++  java
  • 【LeetCode】142

    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?

    Solution:

    Discuss上的分析:Suppose the first meet at step k,the length of the Cycle is r. so..2k-k=nr,k=nrNow, the distance between the start node of list and the start node of cycle is s. the distance between the start of list and the first meeting node is k(the pointer which wake one step at a time waked k steps).the distance between the start node of cycle and the first meeting node ism, so...s=k-m, s=nr-m=(n-1)r+(r-m),here we takes n = 1..so, using one pointer start from the start node of list, another pointer start from the first meeting node, all of them wake one step at a time, the first time they meeting each other is the start of the cycle.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            if(!head || !head->next)return NULL;
            ListNode *faster = head;
            ListNode *slower = head;
            while(faster->next && faster->next->next){
                faster=faster->next->next;
                slower=slower->next;
                if(faster==slower){
                    ListNode *temp=head;
                    while(temp!=slower){
                        temp=temp->next;
                        slower=slower->next;
                    }
                    return temp;
                }
            }
            return NULL;
        }
    };
  • 相关阅读:
    4.28综合练习
    团队项目第一阶段冲刺第六天
    4.27防盗链和代理
    梦断代码阅读笔记3
    团队项目第一阶段冲刺第五天
    4.26抓取猪⼋戒数据
    团队项目第一阶段冲刺第四天
    4.25xpath解析
    4.24aiohttp模块学习
    如何将类数组转化为数组?
  • 原文地址:https://www.cnblogs.com/irun/p/4739753.html
Copyright © 2011-2022 走看看