zoukankan      html  css  js  c++  java
  • 55.链表中环的入口结点(python)

    题目描述

    给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

    思路

    如果slow走了L的长度那么fast走了2L

    假设从开始到入口点的长度是s,slow在环里走的长度是d

    那么 l = s + d

    假设环内slow没走的长度是m,fast走的长度是n*(m+d) + d + s = 2L

    带入得n*(m+d) + d + s = 2(s+d)  =>   s = m+(n-1)(m+d)     m+d就是绕环一圈   所以s = m  所以相遇后,让slow和head一起走,相遇点就是入环节点

     1 class Solution:
     2     def EntryNodeOfLoop(self, pHead):
     3         # write code here
     4         if pHead == None:
     5             return None
     6         fastPointer = pHead
     7         slowPointer = pHead
     8         while fastPointer and fastPointer.next:
     9             slowPointer = slowPointer.next
    10             fastPointer = fastPointer.next.next
    11             if fastPointer == slowPointer:
    12                 break
    13         if fastPointer == None or fastPointer.next == None:
    14             return None
    15         fastPointer = pHead
    16         while fastPointer!=slowPointer:
    17             fastPointer=fastPointer.next
    18             slowPointer=slowPointer.next
    19         return fastPointer

    2019-12-31 22:17:13

  • 相关阅读:
    455. Assign Cookies
    [leetcode]Linked List Cycle
    *[topcoder]GooseTattarrattatDiv1
    [topcoder]FoxAndChess
    *[topcoder]TheTree
    *[topcoder]LittleElephantAndBalls
    *[topcoder]HexagonalBoard
    *[topcoder]AstronomicalRecords
    *[topcoder]LittleElephantAndIntervalsDiv1
    [topcoder]IncrementAndDoubling
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/12127747.html
Copyright © 2011-2022 走看看