题目
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
解题
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
'''
利用列表寻找是否存在重复的对象,时间复杂度O(n),空间复杂度O(n)
if not head:
return head
m = []
while head:
if head in m:
return True
m.append(head)
head = head.next
return False
'''
# 快慢双指针追赶碰撞解法,时间复杂度为O(n),空间复杂度为O(1)
if not head:
return head
slow = head
quick = head
while quick and slow:
# 这里因为quick是跳两次,所以要判断quick和quick.next是否都为空,否则会报NoneType的异常
slow = slow.next
if quick.next:
quick = quick.next.next
else:
return False
if quick is slow:
return True
return False
作者:yu-fa-tang-you-dian-tian
链接:https://leetcode-cn.com/problems/linked-list-cycle/solution/python-pu-tong-lie-biao-de-in-he-shuang-zhi-zhen-k/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。