# 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:
if not head:
return False
#O(N)法
# s = set()
# while head:
# if head in s:
# return True
# s.add(head)
# print(head)
# head = head.next
# 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
总结:本题是环形链表的初级版本,解题思路都是一模一样的,因此不在赘述,想说明的一点就是:检查一个链表是不是有环,还是要用快慢指针法。