快慢指针 解决链表中是否有环,快指针每次走两步,慢指针每次走一步,如果相遇了就证明有环,如果没有相遇(快指针遇到了None)就证明没有环。其中需要注意的是判断空链表,以及快指针为空和即将为空的情况,quick!=None and quick.next!=None

class Solution:
    def hasCycle(self , head ):
        # write code here
        quick=slow=head
        if head==None or head.next==None :
            return False
        while quick!=None and quick.next!=None:
            quick=quick.next.next
            slow=slow.next
            if quick==slow:
                return True
        return False