链表 01. 环形链表

给你一个链表的头节点 head ,判断链表中是否有环。如果链表中存在环 ,则返回 true 。 否则,返回 false 。

方法一:哈希表  时间复杂度O(N)  空间复杂度O(N)

def hasCycle(head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head is None:
            return False

        hash1 = set()
        while head is not None:
            if head not in hash1:
                hash1.add(head)
                head = head.next
            else:
                return True
        return False

方法二:快慢指针  时间复杂度O(N)  空间复杂度O(1)

def hasCycle(head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head is None:
            return False

        slow = head
        fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

方法三取巧:若规定结点数量的上限,则可一直循环,如果计数器超过结点数量上限,则说明有环

posted @ 2022-07-13 14:27  Liang-ml  阅读(18)  评论(0)    收藏  举报