1.题目描述
2.思路
创建一个结点集合,遍历链表,如果遇到已经加进集合的结点就说明链表有环。
3.代码(Python3)
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
node = head
node_set = set()
while node:
if node in node_set:
return True
node_set.add(node)
node = node.next
return False
4.执行情况
5.感想
实在想不到空间复杂度O(1)的算法,看了题解发现这道题特别适合用快慢指针做,如下:
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
作者:灵茶山艾府
链接:https://leetcode.cn/problems/linked-list-cycle/solutions/1999269/mei-xiang-ming-bai-yi-ge-shi-pin-jiang-t-c4sw/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。