Skip to content

Commit c555aa7

Browse files
committed
Swift implementation for LCOF2 022
1 parent 220c483 commit c555aa7

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

lcof2/剑指 Offer II 022. 链表中环的入口节点/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,4 +271,40 @@ var detectCycle = function (head) {
271271
};
272272
```
273273

274+
#### Swift
275+
276+
```swift
277+
/* class ListNode {
278+
* var val: Int
279+
* var next: ListNode?
280+
* init(_ val: Int) {
281+
* self.val = val
282+
* self.next = nil
283+
* }
284+
* }
285+
*/
286+
287+
class Solution {
288+
func detectCycle(_ head: ListNode?) -> ListNode? {
289+
var fast = head
290+
var slow = head
291+
292+
while fast != nil && fast?.next != nil {
293+
slow = slow?.next
294+
fast = fast?.next?.next
295+
296+
if slow === fast {
297+
var ans = head
298+
while ans !== slow {
299+
ans = ans?.next
300+
slow = slow?.next
301+
}
302+
return ans
303+
}
304+
}
305+
return nil
306+
}
307+
}
308+
```
309+
274310
<!-- problem:end -->
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/* class ListNode {
2+
* var val: Int
3+
* var next: ListNode?
4+
* init(_ val: Int) {
5+
* self.val = val
6+
* self.next = nil
7+
* }
8+
* }
9+
*/
10+
11+
class Solution {
12+
func detectCycle(_ head: ListNode?) -> ListNode? {
13+
var fast = head
14+
var slow = head
15+
16+
while fast != nil && fast?.next != nil {
17+
slow = slow?.next
18+
fast = fast?.next?.next
19+
20+
if slow === fast {
21+
var ans = head
22+
while ans !== slow {
23+
ans = ans?.next
24+
slow = slow?.next
25+
}
26+
return ans
27+
}
28+
}
29+
return nil
30+
}
31+
}

0 commit comments

Comments
 (0)