快慢指针。
一个走两个格,一个走一个。若有闭环必相遇。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head or not head.next:
return False
i,j=head,head.next
while j and j.next:
if i==j:
return True
else:
i=i.next
j=j.next.next
return False