Skip to content

Latest commit

 

History

History
47 lines (35 loc) · 1005 Bytes

142.md

File metadata and controls

47 lines (35 loc) · 1005 Bytes

Linked List Cycle 2

Description

link


Solution


Code

T : O(2m + n) S : O(1)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        slow, fast = head, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                slow2 = head
                while slow != slow2:
                    slow = slow.next
                    slow2 = slow2.next
                return slow
            
        return None