给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
#遍历链表,环的存在,遍历遇见的第一个重复的即为入口节点
nodeList = []
while pHead != None:
if pHead not in nodeList:
nodeList.append(pHead)
else:
return pHead
pHead = pHead.next
# -*- 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 pHead == None or pHead.next == None or pHead.next.next == None:
return None
pSlow = pHead.next
pFast = pHead.next.next
# 快慢指针找到相遇点
while pSlow != pFast:
if pFast.next == None or pFast.next.next == None:
return None
pSlow = pSlow.next
pFast = pFast.next.next
pSlow = pHead
# (出发点到入口的距离 = n*圈+相遇点到入口距离)速度相同,重新相遇的地方即为入口
while pSlow != pFast:
pSlow = pSlow.next
pFast = pFast.next
return pSlow