Skip to content

Commit 32ed2d3

Browse files
committed
Add linked-list-cycle-ii solution
1 parent 11f723c commit 32ed2d3

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/leetcode/LinkedListCycleII.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace leetcode;
6+
7+
use leetcode\util\ListNode;
8+
9+
class LinkedListCycleII
10+
{
11+
public static function detectCycle(?ListNode $head): ?ListNode
12+
{
13+
if (!$head) {
14+
return null;
15+
}
16+
$slow = $fast = $head;
17+
while ($fast->next && $fast->next->next) {
18+
$slow = $slow->next;
19+
$fast = $fast->next->next;
20+
if ($slow === $fast) {
21+
$curr = $head;
22+
while ($curr !== $slow) {
23+
$curr = $curr->next;
24+
$slow = $slow->next;
25+
}
26+
return $slow;
27+
}
28+
}
29+
30+
return null;
31+
}
32+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace leetcode\tests;
6+
7+
use leetcode\LinkedListCycleII;
8+
use PHPUnit\Framework\TestCase;
9+
use leetcode\util\ListNode;
10+
11+
class LinkedListCycleIITest extends TestCase
12+
{
13+
public static function testDetectCycle(): void
14+
{
15+
$node1 = new ListNode(3, new ListNode(2, new ListNode(0, new ListNode(-4))));
16+
$list1 = LinkedListCycleII::detectCycle($node1);
17+
self::assertSame([], ListNode::toArray($list1));
18+
19+
$node2 = new ListNode(1, new ListNode(2));
20+
$list2 = LinkedListCycleII::detectCycle($node2);
21+
self::assertSame([], ListNode::toArray($list2));
22+
23+
$node3 = new ListNode(1);
24+
$list3 = LinkedListCycleII::detectCycle($node3);
25+
self::assertSame([], ListNode::toArray($list3));
26+
}
27+
}

0 commit comments

Comments
 (0)