给定一个链表,判断链表中是否有环

2019-02-28  本文已影响0人  mying_三丘

1.开辟字典,有额外空间

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        dict1={}
        if not head or not head.next:
            return False
        count=-1
        while head and head not in dict1:
            count+=1
            dict1[head]=count
            if head.next:
                head = head.next
            else:
                return False
        return True

2.快慢指针,没有额外空间

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:
            return False
        quick=slow=head
        # 下边这个循环不用担心死循环,因为只要出现环,就会被if语句捕捉,不会永远转下去的
        # 若无环,当快指针遍历到最后时,就会结束循环
        while quick.next and quick.next.next:
            quick=quick.next.next
            slow=slow.next
            if quick==slow:
                return True
        return False
上一篇 下一篇

猜你喜欢

热点阅读