题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # first check if it has a loop or not # if it has a loop, return the first position fast meet the slow # else return None def hascycle(head): if not head: return fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: return fast return # slow1 at the head and the slow2 at the first meeting position # the next time they meet is the position where the ring started slow1 = hascycle(pHead) if not slow1: return else: slow2 = pHead while slow2 != slow1: slow1 = slow1.next slow2 = slow2.next return slow2