Swift solution - Two Pointers


  • 0
    class Solution {
        func hasCycle(_ head: ListNode?) -> Bool {
            if head == nil {
                return false
            }
            
            var slow = head
            var fast = head
            
            while fast?.next != nil && fast?.next?.next != nil {
                slow = slow?.next
                fast = fast?.next?.next
                if slow === fast {
                    return true
                }
            }
            
            return false
        }
    }
    

Log in to reply
 

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