leedcode 环形链表

快慢指针:

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        # 如果链表为空或者只有一个节点,肯定不存在环
        if not head or not head.next:
            return False

        # 初始化慢指针和快指针
        slow = head
        fast = head.next

        # 开始循环,直到快指针达到链表末尾
        while slow and fast and fast.next:
            # 如果慢指针和快指针相遇,说明存在环
            if slow == fast:
                return True

            # 移动慢指针一步
            slow = slow.next
            # 移动快指针两步
            fast = fast.next.next

        # 如果循环结束仍未找到相遇点,说明链表中不存在环
        return False

 

posted @ 2024-02-28 10:47  Junior_bond  阅读(5)  评论(0)    收藏  举报