题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路:
1.首先需要判断链表中是否包含环,可以用一快一慢的两个指针,当快的指针追上慢的,说明有环;如果当快的指针到达了尾结点还没有和慢的指针相遇,那么久说明没有环。
2.其次要找出环的入口节点。假设环中有n个节点,从链表的开始设快慢两个指针,让快的指针先走n步,然后两个指针以相同速度移动,当快慢指针相遇时恰好就是环的入口节点。
3.如何得到环中节点的个数呢?当1中快慢指针相遇时肯定是在环内,从这个节点出发,一边继续向前移动一边计数,当再次回到这个节点时,就可以得到环中节点数了。
python题解:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
if not pHead:
return None
mNode=self.judgeLoopRecordMeeting(pHead)
if mNode:
count=self.LoopNodeCount(mNode) #count为节点个数
pPre=pHead
pEnd=pHead
for i in range(0,count): #pPre先走count步
pPre=pPre.next
while pPre!=pEnd:
pPre=pPre.next
pEnd=pEnd.next
return pPre
else:
return None
def judgeLoopRecordMeeting(self,pHead): #如果有循环,返回相遇的节点
pFast=pHead
pSlow=pHead
while pFast.next:
pFast=pFast.next.next
pSlow=pSlow.next
if pFast==pSlow:
return pSlow
return None
def LoopNodeCount(self,pMeet): #找到循环中的节点个数
count=1 #注意这里count的计数
N=pMeet
while N.next!=pMeet:
N=N.next
count=count+1
return count