Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
由于最开始没有弄清楚链表中循环可以从任何位置开始,判断条件是是否tail的值等于head。但是这个题是判断一个链表中是否存在有环,因此这个循环的起始位置是未知的。所以改变了思路,采用两个指针,一个每次走一步,一个每次走两步。如果有回路存在,那么某个时刻两个指针相同。
Runtime: 48 ms
# 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
else:
slow = head
fast = head
while fast.next!= None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False