Merge branch 'master' of github.com:youngyangyang04/leetcode-master

This commit is contained in:
youngyangyang04
2021-08-25 09:42:49 +08:00

View File

@ -296,6 +296,39 @@ var detectCycle = function(head) {
};
```
Swift:
```swift
class Solution {
func detectCycle(_ head: ListNode?) -> ListNode? {
var slow: ListNode? = head
var fast: ListNode? = head
while fast != nil && fast?.next != nil {
slow = slow?.next
fast = fast?.next?.next
if slow == fast {
// 环内相遇
var list1: ListNode? = slow
var list2: ListNode? = head
while list1 != list2 {
list1 = list1?.next
list2 = list2?.next
}
return list2
}
}
return nil
}
}
extension ListNode: Equatable {
public func hash(into hasher: inout Hasher) {
hasher.combine(val)
hasher.combine(ObjectIdentifier(self))
}
public static func == (lhs: ListNode, rhs: ListNode) -> Bool {
return lhs === rhs
}
}
```
-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)