Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def hasCycle(self, head):
 9         """
10         :type head: ListNode
11         :rtype: bool
12         """
13         try:
14             slow = head
15             fast = head.next
16             while slow is not fast:
17                 slow = slow.next
18                 fast = fast.next.next
19             return True
20         except:
21             return False

 

posted on 2017-03-20 19:44  Ci_pea  阅读(103)  评论(0编辑  收藏  举报