一. 题目
-
题目
-
示例
二. 方法一: 集合
-
解题思路
- 将遍历到的每一个节点的地址值都放入到set结合中
- 如果遍历的地址值已经在集合中存在, 则说明存在环
- 如果遍历到列表末尾, 则说明没有环
-
解题代码
def hasCycle(self, head: ListNode) -> bool: res = set() while head: ele = id(head) if ele not in res: res.add(ele) head = head.next else: return True return False
-
分析
时间复杂度: O(n)
空间复杂度: O(n)
三. 方法二: 快慢指针
-
解题思路
- 创建两个指针
- 慢指针每次移动一步; 快指针每次移动两步
- 如果两指针相遇, 则说明存在环
- 如果快指针到达链尾, 则说明没有环
-
解题代码
def hasCycle(self, head: ListNode) -> bool: if not head: return False left = head right = head.next while right and right.next: if left.next != right.next: left = left.next right = right.next.next else: return True else: return False
-
分析
时间复杂度: O(n)
空间复杂度: O(1)