美文网首页
142. Linked List Cycle II

142. Linked List Cycle II

作者: namelessEcho | 来源:发表于2017-09-27 22:02 被阅读0次

    我们要保证快慢指针相遇时的迭代次数相同,于是快慢指针应该时从相同的位置出发,但是循环跳出的条件时相等,于是将快慢指针都前进一次。本题利用了相遇点总是距离环的起点的位置为L-S这一性质。L是环的长度,S是环的入点距离链表起点的位置。

    public class Solution {
        public ListNode detectCycle(ListNode head) {
            if(head==null||head.next==null) return null;
            ListNode fast = head.next.next ;
            ListNode slow = head.next ;
            while(fast!=slow)
            {
                if(fast==null||fast.next==null)
                    return null;
                fast=fast.next.next;
                slow=slow.next;
            }
            // now  meet 
             fast=head;
    
             while(slow!=fast)
            {
                fast=fast.next;
                slow=slow.next;
            }
            return fast;
        }
       
    }
    

    相关文章

      网友评论

          本文标题:142. Linked List Cycle II

          本文链接:https://www.haomeiwen.com/subject/wdmuextx.html