环形链表_双指针

 

 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

 

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
 
  #哈希表
        # hashmap = [] #因为存的是地址
        # if head is None or head.next is None:
        #     return False

 

        # while head:
        #     if head in hashmap:
        #         return True
        #     else:
        #         hashmap.append(head)
        #         head = head.next
        # return False    
        # 

 

        #双指针
        if head is None or head.next is None:
            return False
        slow = fast = head
        while slow and fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow is fast:
                return True
        return False