Skip to content

Commit

Permalink
Reverse Linked List II
Browse files Browse the repository at this point in the history
  • Loading branch information
RamyHakam committed Nov 28, 2021
1 parent 9888f88 commit e6d511d
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
39 changes: 39 additions & 0 deletions LinkedList/ReverseLinkedListII.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace Hakam\LeetCodePhp\LinkedList;
/**
* LeetCode Problem Link : https://leetcode.com/problems/reverse-linked-list-ii
*/
class ReverseLinkedListII
{
/**
* @param ListNode $head
* @param Integer $left
* @param Integer $right
* @return ListNode
*/
public function reverseBetween(ListNode $head, int $left, int $right): ListNode
{
$sentinel = new ListNode(0, $head);
$p1 = $sentinel;

for ($i = 0; $i < $left - 1; $i++) {
$p1 = $p1->next;
}

$p2 = $p1->next;
$p3 = $p2;
$reverted = null;

for ($i = 0; $i <= ($right - $left); $i++) {
$tmp = $p2->next;
$p2->next = $reverted;
$reverted = $p2;
$p2 = $tmp;
}

$p1->next = $reverted;
$p3->next = $p2;
return $sentinel->next;
}
}
10 changes: 10 additions & 0 deletions Tests/Helper/InputFiles/ReverseLinkedListIITest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"testCase1": {
"expectedResult":[1,4,3,2,5],
"input": [[1,2,3,4,5],2,4]
},
"testCase2": {
"expectedResult":[5],
"input": [[5],1,1]
}
}
26 changes: 26 additions & 0 deletions Tests/LinkedList/ReverseLinkedListIITest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace Hakam\LeetCodePhp\Tests\LinkedList;

use Hakam\LeetCodePhp\LinkedList\ReverseLinkedListII;
use Hakam\LeetCodePhp\Tests\Helper\LinkedListHelperTrait;
use Hakam\LeetCodePhp\Tests\Helper\MainTest;

/**
* @covers \Hakam\LeetCodePhp\LinkedList\ReverseLinkedListII
*/
class ReverseLinkedListIITest extends MainTest
{
use LinkedListHelperTrait;

/**
* @dataProvider provideData
*/
public function testWithDataList($expectedResult, $inputData): void
{
$reversList = new ReverseLinkedListII();
$list = $this->convertFromArray($inputData[0]);
self::assertEmpty(array_diff($expectedResult,
$this->convertToArray($reversList->reverseBetween($list,$inputData[1],$inputData[2]))));
}
}

0 comments on commit e6d511d

Please sign in to comment.