1. 快慢指针

class Solution:
    def hasCycle(self , head ):
        if not head:
            return False
        slow = head;
        fast = head;
        while fast and fast.next :
            slow = slow.next
            fast = fast.next.next
            if (slow == fast):
                return True
        return False

2. 使用集合的方式

把所有的node加入到集合中,如果最后遍历出的node已经存在于集合中,则说明有环,反之则无环

class Solution:
    def hasCycle(self , head ):
        if not head:
            return False
        setCycle = set()
        while head:
            if head in setCycle:
                return True
            setCycle.add(head)
            head = head.next
        return False