https://leetcode.com/problems/linked-list-cycle/
参考http://www.cnblogs.com/zuoyuan/p/3701639.html
一开始我错误的code:
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head : return False
slow, fast = head, head
while fast and fast.next and fast != slow:#这里这个条件fast!=slow,使得在一开始就无法进入循环
slow = slow.next
fast = fast.next.next
if fast == None or fast.next == None:
return False
else:
return True
正确的code:
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head : return False
slow, fast = head, head
while fast.next and fast.next.next:#这里用fast and fast.next也可以
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False