/** 链表节点 */ classListNode { var val: Int var next: ListNode? init(_val: Int) { self.val = val self.next =nil } }
/** LeetCode-142.查找链表中的环的入口*/ funcdetectCycle(_head: ListNode?) -> ListNode? { var slow = findCycleNode(head) guard slow !==nilelse { returnnil } var fast = head while fast !== slow { fast = fast?.next slow = slow?.next } return slow } // 查找链表中快慢指针相遇的节点 funcfindCycleNode(_head: ListNode?) -> ListNode? { if head ==nil { returnnil } var fast = head var slow = head while fast !==nil&& fast?.next !==nil { fast = fast?.next?.next slow = slow?.next if fast === slow { return slow } } returnnil }