空间复杂度O(1): 快指针追上慢指针即可确定有回环
# 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:
l1 = head
l2 = head
while(l2 != None and l2.next != None):
l1 = l1.next
l2 = l2.next.next
if l1 == l2:
return True
return False
空间复杂度O(N):比较简单,直接用哈希记录即可