题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
from heapq import heapify # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryNodeOfLoop(self, pHead): node = self.hasCycle(pHead) p = pHead if node: while p != node: p = p.next node = node.next return p else: return None def hasCycle(self, pHead): # write code here fast = pHead slow = pHead while fast and slow: if fast and fast.next: slow = slow.next fast = fast.next.next else: return None if fast == slow: return slow return None
环问题:如何找到环的起始点。先找到相遇点 让快慢指针同时分别从头结点和相遇点以相同的速度出发,再次相遇点即为起点。