# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
hasLoop = self.hasLoop(pHead)
if hasLoop == None:
return None
n = self.nodeNum(hasLoop)
fast = slow = pHead
for i in range(n):
fast = fast.next
while fast != slow:
fast = fast.next
slow = slow.next
return slow
def hasLoop(self, pHead):
if pHead == None or pHead.next == None:
return None
slow, fast = pHead, pHead.next
while fast != None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return slow
return None
def nodeNum(self, pHead):
p = pHead.next
n = 1
while p != pHead:
p = p.next
n += 1
return n
网友评论