2019-05-18LeetCode141. 环形链表
2019-05-18 本文已影响0人
mztkenan
25min,双指针,对链表的处理,关键点在于a.next 的时候 a 不能是None,特殊情况head 为空
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if(head!=None):pos=head.next
else:return False # head=None
while(pos!=head):
if(head!=None):
head=head.next
else:return False
if(pos!=None and pos.next!=None):
pos=pos.next.next
else:return False
return True
使用try catch简直优雅,因为所有的异常情况都表示无环!excellent!
Easier to ask for forgiveness than permission."
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
try:
fast=head.next
while(fast!=head):
fast=fast.next.next
head=head.next
return True
except:
return False