判断是否有环时,循环条件是fast is not None and fast.next is not None
求入环点时,循环条件是fast != slow
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
slow=self.hasCycle(head)
if slow==None:
return None
#当fast与slow相遇,表明链表有环,但相遇点不是入环点
#相遇时,让快指针回到头结点,重新1步1步往前走,当快慢指针再次相遇,就是入环点
fast=head
while fast != slow:
fast=fast.next
slow=slow.next
return slow
def hasCycle(self,head):
if head==None:
return None
#快指针走2步,慢指针走1步,当他们相遇,表明链表有环
slow=head
fast=head
#链表有环,起码有2个值
while fast is not None and fast.next is not None:
slow=slow.next
fast=fast.next.next
if slow == fast:
return slow
return None