Test Failed
Push — master ( 6df6de...29cfea )
by Jinyun
02:32
created

RemoveNthNodeFromEndOfList::removeNthFromEnd()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 18
rs 9.8666
cc 4
nc 5
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\ListNode;
8
9
class RemoveNthNodeFromEndOfList
10
{
11
    public static function removeNthFromEnd(?ListNode $head, int $n): ?ListNode
12
    {
13
        if (!$head) {
14
            return null;
15
        }
16
        $node = new ListNode();
17
        $node->next = $head;
18
        $slow = $fast = $node;
19
        for ($i = 1; $i <= $n + 1; $i++) {
20
            $fast = $fast->next;
21
        }
22
        while ($fast) {
23
            $slow = $slow->next;
24
            $fast = $fast->next;
25
        }
26
        $slow->next = $slow->next->next;
27
28
        return $node->next;
29
    }
30
31
    public static function removeNthFromEnd2(?ListNode $head, int $n): ?ListNode
32
    {
33
        if (!$head) {
34
            return null;
35
        }
36
        $slow = $fast = $head;
37
        for ($i = 0; $i < $n; $i++) {
38
            $fast = $fast->next;
39
        }
40
        if (!$fast) {
41
            return $head->next;
42
        }
43
        while ($fast->next) {
44
            $slow = $slow->next;
45
            $fast = $fast->next;
46
        }
47
        $slow->next = $slow->next->next;
48
49
        return $head;
50
    }
51
}
52