其他分享
首页 > 其他分享> > 检查链表是否有环

检查链表是否有环

作者:互联网

快慢指针 时间复杂度O(N),空间复杂度O(1)

class Solution:
def hasCycle(self , head):
# write code here
if head == None or head.next == None:
return False
slow = head
fast = head.next
while (fast.next != None and fast.next.next != None) and (slow != fast):
slow = slow.next # 慢指针一次走一步
fast = fast.next.next # 快指针一次走两步
if slow == fast: # 若有环,必会有slow==fast
return True
else:
return False

标签:head,slow,return,检查,None,fast,next,链表,有环
来源: https://blog.csdn.net/vdrujf/article/details/117792130