用一个 set 存储已经遍历过的节点,如果遍历到的节点已经在 set 中,说明链表有环。如果没有环,遍历到 None 时退出循环返回 False。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head: Optional[ListNode]) -> bool: seen = set() while head isnotNone: if head in seen: returnTrue seen.add(head) head = head.next returnFalse