zoukankan      html  css  js  c++  java
  • LeetCode 142. Linked List Cycle II 20170706

    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.

    题目大意:给定一个链表,如果该链表存在环,返回环的起点。如果不存在,返回null

    解题思路:本题是一道有趣的行程问题。在这里给出该行程问题的推导。

    假设有两个快慢指针fast和slow,其中fast一次走两步,slow一次走一步,两者同时出发,由于存在环,所以必定会在某点相遇。设head到环起点距离为a,起点距离到相遇点距离为b,环长度为c。则fasts=2slows,slows=a+b,fasts=a+b+n*c,所以可知slows=n*c,a=n*c-b。当相遇后,令slow返回head,两者同时以每次一步的速度前进。slow从head走到起点走了a,fast也相遇点走了a,因为a=n*c-b=(n-1)*c+c-b,所以可知a+b=n*c,fast恰好也走回了起点。这样就能把每个变量都求出来,就能求出起点位置了。

    class Solution(object):
      def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
          return None
        slow = fast = head
        while fast and fast.next:
          slow = slow.next
          fast = fast.next.next
          if fast == slow:
            break
        if slow == fast:
          slow = head
          while slow != fast:
            slow = slow.next
            fast = fast.next
          return slow
        return None

  • 相关阅读:
    个人介绍
    C++ 之 第四课 C++中的运算符、表达式
    Delphi 之 第六课 过程与函数
    Delphi 之 第五课 流程语句
    VB 之 第三课 VB API 字体函数的应用
    C++ 之 第三课 C++数据类型
    Delphi 之 第四讲 自定义数据类型
    Delphi 之 第三课 详解数据类型
    C++ 之 第二课 C++类、函数的讲解
    VB API 第二课 之 字符串大小写转换
  • 原文地址:https://www.cnblogs.com/fangdai/p/7125308.html
Copyright © 2011-2022 走看看