Test Failed
Push — master ( e37232...aa116f )
by Jinyun
03:02
created

RemoveLinkedListElements::removeElements2()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 21
rs 9.4888
cc 5
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 RemoveLinkedListElements
10
{
11
    public static function removeElements(?ListNode $head, int $val): ?ListNode
12
    {
13
        if (!$head) {
14
            return null;
15
        }
16
        $next = self::removeElements($head->next, $val);
17
        if ($head->val === $val) {
18
            return $next;
19
        }
20
        $head->next = $next;
21
22
        return $head;
23
    }
24
25
    public static function removeElements2(?ListNode $head, int $val): ?ListNode
26
    {
27
        if (!$head) {
28
            return null;
29
        }
30
        [$prev, $curr] = [null, $head];
31
        while ($curr) {
32
            if ($curr->val === $val) {
33
                if ($curr === $head) {
34
                    $curr = $head = $head->next;
35
                } else {
36
                    $prev->next = $curr->next;
37
                    $curr = $curr->next;
38
                }
39
            } else {
40
                $prev = $curr;
41
                $curr = $curr->next;
42
            }
43
        }
44
45
        return $head;
46
    }
47
48
    public static function removeElements3(?ListNode $head, int $val): ?ListNode
49
    {
50
        if (!$head) {
51
            return null;
52
        }
53
        $dummy = new ListNode();
54
        $dummy->next = $head;
55
        [$prev, $curr] = [$dummy, $head];
56
        while ($curr) {
57
            if ($curr->val === $val) {
58
                $prev->next = $curr->next;
59
            } else {
60
                $prev = $prev->next;
61
            }
62
            $curr = $curr->next;
63
        }
64
65
        return $dummy->next;
66
    }
67
68
    public static function removeElements4(?ListNode $head, int $val): ?ListNode
69
    {
70
        if (!$head) {
71
            return null;
72
        }
73
        $curr = $head;
74
        while ($curr->next) {
75
            if ($curr->next->val === $val) {
76
                $curr->next = $curr->next->next;
77
            } else {
78
                $curr = $curr->next;
79
            }
80
        }
81
82
        return $head->val === $val ? $head->next : $head;
83
    }
84
}
85