环形链表()

法一:
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

 

posted on 2020-08-19 16:22  不要挡着我晒太阳  阅读(95)  评论(0编辑  收藏  举报

导航