题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 先判断链表是否有环,快慢指针
def ifLoop(self ,head : ListNode) -> bool:
if not head:
return None
fast=head
slow=head
while fast and slow:
slow=slow.next
if fast.next:
fast=fast.next.next
else:
return None
if fast==slow:
return slow
return None
# 快慢指针各移动一步,两者重合时的位置,即为环的入口
def EntryNodeOfLoop(self, pHead:ListNode):
# write code here
slow=self.ifLoop(pHead) # slow的位置是判断环表结束时的位置
if not slow:
return None
fast=pHead # fast 重新定位在头节点
while fast!=slow:
fast=fast.next
slow=slow.next
return slow
