-
Notifications
You must be signed in to change notification settings - Fork 21
/
LinkedListCycleII.swift
53 lines (45 loc) 路 1.22 KB
/
LinkedListCycleII.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//
// LinkedListCycleII.swift
// LeetCode
//
// Created by 榛庤档澶儙 on 28/02/2018.
// Copyright 漏 2018 lizhaotailang. All rights reserved.
//
// Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
//
// Note: Do not modify the linked list.
//
// Follow up:
// Can you solve it without using extra space?
//
// See [LinkedListCycleIITests](./LeetCodeTests/LinkedListCycleIITests.swift) for test cases.
//
import Foundation
class LinkedListCycleII {
// Waiting to be judged.
func detectCycle(_ head: ListNode?) -> ListNode? {
var slow = head
var fast = head
var h = head
while fast != nil && fast?.next != nil {
slow = slow?.next
fast = fast?.next?.next
if slow === fast {
while slow !== head {
h = h?.next
slow = slow?.next
}
return h
}
}
return nil
}
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
}