Swift solution - Two Pointers


  • 0
    class Solution142 {
        func detectCycle(_ head: ListNode?) -> ListNode? {
            if head == nil || head?.next == nil {
                return nil
            }
            
            var slow = head
            var fast = head
            var entry = head
            
            while fast?.next != nil && fast?.next?.next != nil {
                slow = slow?.next
                fast = fast?.next?.next
                
                if slow === fast {
                    while !(slow === entry) {
                        slow = slow?.next
                        entry = entry?.next
                    }
                    return entry
                }
            }
            
            return nil
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.