思路:快慢指针,快的每次走两步,慢的每次走一步,如果是环形链表,则总有一天快慢指针会指向同一个结点。
# 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==None:
return False
fast=slow=head
while fast.next!=None and fast.next.next!=None:
fast=fast.next.next
slow=slow.next
if fast==slow:
return True
return False