LeetCode题目地址
具体代码
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val x # self.next None class Solution(object): def hasCycle(self, head): slow fast head # 链表不为空 if head is not None: if fast.next is None: return False fast fast.next.next while fast: if slow fast: return True slow slow.next if fast.next is None: return False fast fast.next.next return False return False总结
有一点需要注意 我先开始用的是双指针 也就是一个指针走两步 一个指针走一步 通过这种方式来判断它是否有环。
但是在写代码时 如果给定的测试用例是单数 则会报错哦。因为它要走两步slow.next.next。如果这个slow如果在末尾 它第一次next就已经是None了 也就不存在next了 因此需要多加一行if fast.next is None: 这一点需要注意。



