142. 环形链表 II

题目链接 142. 环形链表 II
思路 快慢指针-经典应用:相遇后,移动headslow直至相遇
题解链接 没想明白?一个视频讲透!含数学推导(Python/Java/C++/Go/JS)
关键点 while fast and fast.next: ... && while head != slow: ...
时间复杂度 \(O(n)\)
空间复杂度 \(O(1)\)

代码实现:

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast is slow:
                while slow is not head:
                    slow = slow.next
                    head = head.next
                return head
        return None
posted @ 2024-09-11 22:23  WrRan  阅读(4)  评论(0编辑  收藏  举报