-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPalindromeLinkedList.php
More file actions
72 lines (63 loc) · 1.51 KB
/
PalindromeLinkedList.php
File metadata and controls
72 lines (63 loc) · 1.51 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
namespace leetcode;
use leetcode\util\ListNode;
class PalindromeLinkedList
{
public static function isPalindrome(ListNode $head): bool
{
$fast = $head;
$slow = $head;
while ($fast && $fast->next) {
$fast = $fast->next->next;
$slow = $slow->next;
}
if ($fast) {
$slow = $slow->next;
}
$fast = $head;
$slow = self::helper($slow);
while ($slow) {
if ($fast->val !== $slow->val) {
return false;
}
$fast = $fast->next;
$slow = $slow->next;
}
return true;
}
/**
* Note: Time Limit Exceeded.
*
* @param \leetcode\util\ListNode $head
*
* @return bool
*/
public static function isPalindrome2(ListNode $head): bool
{
$node = $head;
$queue = [];
while ($node) {
array_push($queue, $node);
$node = $node->next;
}
while (count($queue) >= 2) {
[$p, $q] = [array_shift($queue), array_pop($queue)];
if ($p && $q && $p->val != $q->val) {
return false;
}
}
return true;
}
private static function helper(ListNode $head): ?ListNode
{
$prev = null;
while ($head) {
$next = $head->next;
$head->next = $prev;
$prev = $head;
$head = $next;
}
return $prev;
}
}