141. 环形链表

https://leetcode-cn.com/problems/linked-list-cycle/

解法一:快慢指针

一个slow一个fast,slow每次走一步,fast每次走两步,若有环,slow和fast必会相遇(slow每次两步,fast每次三步也可以,重要的是步差为1,若步差为2则可能超时)

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:  #边界
            return False
        #初始化
        slow = head
        fast = head.next
        while slow != fast:
            #若走到尽头(注意fast肯定是走在前面的,用fast来检测,必须保证fast两步之内全部合法)
            if not fast or not fast.next:
                return False
            slow = slow.next
            fast = fast.next.next
        return True

slow每次2步,fast每次3步:

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:
            return False
        slow = head
        fast = head.next
        while slow != fast:
            #必须保证fast三步之内全部合法
            if not fast or not fast.next or not fast.next.next:
                return False
            slow = slow.next.next
            fast = fast.next.next.next
        return True

也可以开始就令快慢指针同一起点出发(比上面写法简洁):

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:  #边界
            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

最后更新于