Test Failed
Push — master ( f38782...f110ed )
by Jinyun
02:42
created

LinkedListCycleII::detectCycle()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 20
rs 9.2222
cc 6
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\ListNode;
8
9
class LinkedListCycleII
10
{
11
    public static function detectCycle(?ListNode $head): ?ListNode
12
    {
13
        if (!$head) {
14
            return null;
15
        }
16
        $slow = $fast = $head;
17
        while ($fast->next && $fast->next->next) {
18
            $slow = $slow->next;
19
            $fast = $fast->next->next;
20
            if ($slow === $fast) {
21
                $curr = $head;
22
                while ($curr !== $slow) {
23
                    $curr = $curr->next;
24
                    $slow = $slow->next;
25
                }
26
                return $slow;
27
            }
28
        }
29
30
        return null;
31
    }
32
}
33