LC 速查

HOT 100索引 › B7 链表 Linked List

LC 141环形链表Linked List Cycle 简单

判断链表中是否存在环,即沿 next 是否会再次回到某个节点。

思路 快慢指针,快每次两步;相遇则有环,快到 null 则无环。时间 O(n)。

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
← 上一题 回文链表环形链表 II 下一题 →