环形链表判断

方法一:

哈希表

时间复杂度:O(n)

空间复杂度:O(n)

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        dict = {}
        while head:
            if head in dict:
                return True
            else:
                dict.setdefault(head,1)
                head = head.next
        return False

方法二:

快慢指针

时间复杂度:O(n)

空间复杂度:O(1)

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        slow = head
        fast = head
        while  fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False
posted @ 2020-06-25 04:24  guguda  阅读(108)  评论(0)    收藏  举报