题目内容
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出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 not pHead:
return None
fast,slow=pHead,pHead
while fast and fast.next:
fast=fast.next.next
slow=slow.next
if fast==slow:
res=pHead
while res!=slow:
res=res.next
slow=slow.next
return res
return None#说明不包含环