Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断链表是否有环的技巧:一个走两步,一个走一步,查看是否汇合
class Solution(object):
def hasCycle(self, head):
p = head
q = head
has_cycle = False
try:
while(p and p.next):
p = p.next
q = q.next.next
if p == q:
has_cycle = True
break
except AttributeError:
pass
return has_cycle