-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMergeTwoSortedLists.php
47 lines (40 loc) · 1.03 KB
/
MergeTwoSortedLists.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
declare(strict_types=1);
namespace leetcode;
use JetBrains\PhpStorm\Pure;
use leetcode\util\ListNode;
class MergeTwoSortedLists
{
public static function mergeTwoLists(?ListNode $p, ?ListNode $q): ?ListNode
{
if (!$p || !$q) {
return $p ?: $q;
}
if ($p->val < $q->val) {
$p->next = self::mergeTwoLists($p->next, $q);
return $p;
} else {
$q->next = self::mergeTwoLists($p, $q->next);
return $q;
}
}
public static function mergeTwoLists2(?ListNode $p, ?ListNode $q): ?ListNode
{
if (!$p || !$q) {
return $p ?: $q;
}
$head = $curr = new ListNode();
while ($p && $q) {
if ($p->val < $q->val) {
$curr->next = $p;
$p = $p->next;
} else {
$curr->next = $q;
$q = $q->next;
}
$curr = $curr->next;
}
$curr->next = $p ?: $q;
return $head->next;
}
}