Test Failed
Push — master ( 1d696c...5ff2ef )
by Jinyun
02:35
created

MergeTwoSortedLists::mergeTwoLists2()   B

Complexity

Conditions 8
Paths 4

Size

Total Lines 19
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 19
rs 8.4444
cc 8
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use JetBrains\PhpStorm\Pure;
8
use leetcode\util\ListNode;
9
10
class MergeTwoSortedLists
11
{
12
    public static function mergeTwoLists(?ListNode $p, ?ListNode $q): ?ListNode
13
    {
14
        if (!$p || !$q) {
15
            return $p ?: $q;
16
        }
17
18
        if ($p->val < $q->val) {
19
            $p->next = self::mergeTwoLists($p->next, $q);
20
            return $p;
21
        } else {
22
            $q->next = self::mergeTwoLists($p, $q->next);
23
            return $q;
24
        }
25
    }
26
27
    public static function mergeTwoLists2(?ListNode $p, ?ListNode $q): ?ListNode
28
    {
29
        if (!$p || !$q) {
30
            return $p ?: $q;
31
        }
32
        $head = $curr = new ListNode();
33
        while ($p && $q) {
34
            if ($p->val < $q->val) {
35
                $curr->next = $p;
36
                $p = $p->next;
37
            } else {
38
                $curr->next = $q;
39
                $q = $q->next;
40
            }
41
            $curr = $curr->next;
42
        }
43
        $curr->next = $p ?: $q;
44
45
        return $head->next;
46
    }
47
}
48