Skip to content

Commit dcb263b

Browse files
committed
Add palindrome-linked-list solution
1 parent b797585 commit dcb263b

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed

Diff for: src/leetcode/PalindromeLinkedList.php

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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);
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+
}

Diff for: tests/leetcode/PalindromeLinkedListTest.php

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace leetcode\tests;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use leetcode\PalindromeLinkedList;
9+
use leetcode\util\ListNode;
10+
11+
class PalindromeLinkedListTest extends TestCase
12+
{
13+
public function testIsPalindrome(): void
14+
{
15+
$head1 = new ListNode(1, new ListNode(2, new ListNode(2, new ListNode(1))));
16+
self::assertTrue(PalindromeLinkedList::isPalindrome($head1));
17+
18+
$head2 = new ListNode(1, new ListNode(2));
19+
self::assertFalse(PalindromeLinkedList::isPalindrome($head2));
20+
}
21+
22+
public function testIsPalindrome2(): void
23+
{
24+
$head1 = new ListNode(1, new ListNode(2, new ListNode(2, new ListNode(1))));
25+
self::assertTrue(PalindromeLinkedList::isPalindrome2($head1));
26+
27+
$head2 = new ListNode(1, new ListNode(2));
28+
self::assertFalse(PalindromeLinkedList::isPalindrome2($head2));
29+
}
30+
}

0 commit comments

Comments
 (0)