LeetCode判断一个单向链表是否有环?Swift 面试

快慢双指针法,快指针一次走两步,慢指针一次走一步,如果有环必会相遇

 public class ListNode {
     public var val: Int
     public var next: ListNode?
     public init(_ val: Int) {
         self.val = val
         self.next = nil
     }
 }

func validedCycleNoded(_ node: ListNode?) -> Bool {
    if node == nil {
        return false
    }

    var fast = node, slow = node

    while fast != nil {
        fast = fast?.next?.next
        slow = slow?.next

        if fast?.val == slow?.val {
            return true
        }
    }

    return false
}

 

posted @ 2020-11-18 10:05  黄增松  阅读(132)  评论(0编辑  收藏  举报