使用快慢指针,如果由环,那么快指针会和慢指针指向同一个节点。
# 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):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None:
return False
slow = head
fast = head
while slow and fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
else:
return False
if slow == fast:
return True
return False