法一:
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        a = set() 
        while head:
            
            if head in a:
                return True

            a.add(head)
            head = head.next
        return False



法二:
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        slow = fast = head
        # if not head:  # 没必要这样写可以加入while循环判断更简洁
        #     return False

        while fast and fast.next:  # 防止head为空和出现空指针的next的情况
            slow = slow.next
            fast = fast.next.next
            if slow is fast:
                return True

        return False

 

相关文章:

  • 2022-03-06
  • 2021-02-17
  • 2022-12-23
  • 2020-07-20
  • 2021-08-25
  • 2021-05-04
猜你喜欢
  • 2022-12-23
  • 2020-02-27
相关资源
相似解决方案