Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
<思路>判断是否是循环链表。用fast(2步)和slow(1步)两个循环去判断,如果节点相等,肯定有循环存在,否则slow追不上fast。
如果没有循环链表,那fast会先走到头,然后停止while循环,返回False。
# 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
"""
fast = slow = head
while fast and slow:
try:
fast = fast.next.next
slow = slow.next
except:
return False
if fast == slow:
return True
return False