0%

Leetcode 141 环形链表 I

给你一个链表的头节点 head ,判断链表中是否有环。

用一个 set 存储已经遍历过的节点,如果遍历到的节点已经在 set 中,说明链表有环。如果没有环,遍历到 None 时退出循环返回 False

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
seen = set()
while head is not None:
if head in seen:
return True
seen.add(head)
head = head.next
return False