题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出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
if pHead == None or pHead.next==None or pHead.next.next==None:
return None
low = pHead.next
fast = pHead.next.next
while low!=fast:
low = low.next
fast = fast.next.next
fast = pHead
while low!=fast:
low = low.next
fast = fast.next
return fast