zoukankan      html  css  js  c++  java
  • leetcode 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?

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

    方法:

    第一次相遇时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,也就是说,从一开始到二者第一次相遇,循环的次数就等于环的长度。

    我们已经得到了结论a=c,那么让两个指针分别从X和Z开始走,每次走一步,那么正好会在Y相遇!也就是环的第一个节点。

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode detectCycle(ListNode head) {
            if(head == null || head.next == null){
                return null;
            }
            
            ListNode fast = head, slow = head;
            
            while(1 == 1){
                if(fast == null || fast.next ==null) return null;
                
                fast = fast.next.next;
                slow = slow.next;
                if(fast == slow){
                    break;
                }
            }
            
            slow = head;
            while(fast != slow){
                fast = fast.next;
                slow = slow.next;
            }
            
            return slow;
            
        }
    }

    或者

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode detectCycle(ListNode head) {
            if(head == null || head.next == null){
                return null;
            }
            
            ListNode fast = head.next, slow = head;
            
            while(fast != slow){
                if(fast == null || fast.next ==null) return null;
                
                fast = fast.next.next;
                slow = slow.next;
            }
            
            
            while(head != slow.next){
                head = head.next;
                slow = slow.next;
            }
            
            return head;
            
        }
    }
  • 相关阅读:
    下载及爬取网页内容
    对于for循环的理解
    记录安装fiddle出现的问题
    Django
    12种可以参考的思路关于代码能干什么
    “字符文本中字符太多”错误及解决方法
    jQuery参考:jquery中的$(document).ready()与window.onload的区别
    页面定时刷新功能实现
    HTML:关于位置的几个概念
    Lambda表达式
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5695380.html
Copyright © 2011-2022 走看看