zoukankan      html  css  js  c++  java
  • 【链表】Linked List Cycle II

    题目:

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

    思路:

    第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。

    因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。

    我们发现L=b+c=a+b,也就是说,从一开始到二者第一次相遇,循环的次数就等于环的长度。

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var detectCycle = function(head) {
        if(head==null){
            return null;
        }
        if(head.next==null){
            return head;
        }
        
        var s=head,f=head.next.next;
        while(s!=f){
            if(f==null||f.next==null){
                return null;
            }else{
                s=s.next;
                f=f.next.next;
            }
        }
        
        s=head;
        while(s!=f){
            s=s.next;
            f=f.next;
        }
        return s;
    
    };
  • 相关阅读:
    快速排序算法
    DirectX9(翻译):介绍
    奇葩的面试题
    新博客
    OpenCV2:幼儿园篇 第八章 视频操作
    编程规范:位运算
    编程规范:allocator
    深浅copy和浅copy
    模块和包
    递归函数
  • 原文地址:https://www.cnblogs.com/shytong/p/5156903.html
Copyright © 2011-2022 走看看