mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
添加 142.环形链表II Swift版本
This commit is contained in:
@ -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)
|
||||
|
Reference in New Issue
Block a user