链表中环的入口结点 牛客网 剑指Offer
链表中环的入口结点 牛客网 剑指Offer
- 题目描述
- 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
if pHead == None:
return None
pSlow = pHead.next
if pSlow == None:
return None
pFast = pSlow.next
while pFast:
if pSlow == pFast:
break
pSlow = pSlow.next
pFast = pFast.next
if pFast:
pFast = pFast.next
NodeLoop = 1
flagNode = pSlow
while flagNode.next != pSlow:
NodeLoop += 1
flagNode = flagNode.next
pFirst = pHead
for i in range(NodeLoop):
pFirst = pFirst.next
pSecond = pHead
while pFirst != pSecond:
pFirst = pFirst.next
pSecond = pSecond.next
return pFirst