題目描述
給一個鏈表,若其中包含環,請找出該鏈表的環的入口結點,否則,輸出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