返回环形链表的入环结点

    科技2022-07-16  126

    套路:

    快慢指针,当两指针相遇时,快指针回到头结点,两个指针继续同步移动一步,直到第二次相遇即为所求。

    class Solution: def detectCycle(self, head: ListNode) -> ListNode: if not head or not head.next: return fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: fast = head while fast != slow: fast = fast.next slow = slow.next return slow return

     

    Processed: 0.012, SQL: 8