这篇说得挺好的
https://blog.csdn.net/liuchonge/article/details/73520414
两种方法都是O(n)时间和O(1)空间,根据思想用python写了一遍
- 法1
# 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
cur=head
post=cur.next
while post:
cur.next=head
cur=post
post=cur.next
if post==head:
return True
return False
- 法二 快慢指针
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head==None or head.next==None:
return False
fast=low=head
while fast:
try:
low=low.next
fast=fast.next.next
except :
return False
if fast==low:
return True
return False
- 其中快慢指针我已经修改成了带一点点EAFP的思想的,但是还是没有discussion上面的大佬写得好啊T.T
#高票代码
def hasCycle(self, head):
try:
slow = head
fast = head.next
while slow is not fast:
slow = slow.next
fast = fast.next.next
return True
except:
return False
大概的思想就是:除了slow==fast能表明有环以外,其他任意的情况(fast行走过程中遇到了None,或者head是空指针
)都表明无环
EAFP(easier to ask for forgiveness better than permission)原则和LBYL(look before you leap)原则在python的Glossory上都有,具体的例子见stackoverflow的一个回答