-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRemoveNthNodeFromEndOfList.php
More file actions
51 lines (44 loc) · 1.09 KB
/
RemoveNthNodeFromEndOfList.php
File metadata and controls
51 lines (44 loc) · 1.09 KB
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
48
49
50
51
<?php
declare(strict_types=1);
namespace leetcode;
use leetcode\util\ListNode;
class RemoveNthNodeFromEndOfList
{
public static function removeNthFromEnd(?ListNode $head, int $n): ?ListNode
{
if (!$head) {
return null;
}
$node = new ListNode();
$node->next = $head;
$slow = $fast = $node;
for ($i = 1; $i <= $n + 1; $i++) {
$fast = $fast->next;
}
while ($fast) {
$slow = $slow->next;
$fast = $fast->next;
}
$slow->next = $slow->next->next;
return $node->next;
}
public static function removeNthFromEnd2(?ListNode $head, int $n): ?ListNode
{
if (!$head) {
return null;
}
$slow = $fast = $head;
for ($i = 0; $i < $n; $i++) {
$fast = $fast->next;
}
if (!$fast) {
return $head->next;
}
while ($fast->next) {
$slow = $slow->next;
$fast = $fast->next;
}
$slow->next = $slow->next->next;
return $head;
}
}