PalindromeLinkedList   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 14
eloc 33
c 1
b 0
f 0
dl 0
loc 62
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A helper() 0 11 2
A isPalindrome() 0 22 6
A isPalindrome2() 0 16 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\ListNode;
8
9
class PalindromeLinkedList
10
{
11
    public static function isPalindrome(ListNode $head): bool
12
    {
13
        $fast = $head;
14
        $slow = $head;
15
        while ($fast && $fast->next) {
16
            $fast = $fast->next->next;
17
            $slow = $slow->next;
18
        }
19
        if ($fast) {
20
            $slow = $slow->next;
21
        }
22
        $fast = $head;
23
        $slow = self::helper($slow);
0 ignored issues
show
Bug introduced by
It seems like $slow can also be of type null; however, parameter $head of leetcode\PalindromeLinkedList::helper() does only seem to accept leetcode\util\ListNode, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

23
        $slow = self::helper(/** @scrutinizer ignore-type */ $slow);
Loading history...
24
        while ($slow) {
25
            if ($fast->val !== $slow->val) {
26
                return false;
27
            }
28
            $fast = $fast->next;
29
            $slow = $slow->next;
30
        }
31
32
        return true;
33
    }
34
35
    /**
36
     * Note: Time Limit Exceeded.
37
     *
38
     * @param \leetcode\util\ListNode $head
39
     *
40
     * @return bool
41
     */
42
    public static function isPalindrome2(ListNode $head): bool
43
    {
44
        $node = $head;
45
        $queue = [];
46
        while ($node) {
47
            array_push($queue, $node);
48
            $node = $node->next;
49
        }
50
        while (count($queue) >= 2) {
51
            [$p, $q] = [array_shift($queue), array_pop($queue)];
52
            if ($p && $q && $p->val != $q->val) {
53
                return false;
54
            }
55
        }
56
57
        return true;
58
    }
59
60
    private static function helper(ListNode $head): ?ListNode
61
    {
62
        $prev = null;
63
        while ($head) {
64
            $next = $head->next;
65
            $head->next = $prev;
66
            $prev = $head;
67
            $head = $next;
68
        }
69
70
        return $prev;
71
    }
72
}
73