Skip to content

Commit

Permalink
Remove Nth Node From End Of List
Browse files Browse the repository at this point in the history
  • Loading branch information
RamyHakam committed Nov 26, 2021
1 parent d38dbe3 commit 9888f88
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 1 deletion.
3 changes: 2 additions & 1 deletion LinkedList/ListNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

/**
* @covers \Hakam\LeetCodePhp\LinkedList\ListNode
* @codeCoverageIgnore
*/
class ListNode
{
Expand All @@ -13,7 +14,7 @@ class ListNode
/**
* @param int $val
* @param null $next
* @codeCoverageIgnore
*/
public function __construct($val = 0, $next = null)
{
Expand Down
33 changes: 33 additions & 0 deletions LinkedList/RemoveNthNodeFromEndOfList.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Hakam\LeetCodePhp\LinkedList;

class RemoveNthNodeFromEndOfList
{
/**
* @param ListNode $head
* @param Integer $n
* @return ListNode
*/
public function removeNthFromEnd(ListNode $head, int $n) : ?ListNode
{
$dummy = new ListNode(0);
$dummy->next = $head;
$copyHead = $head;
$length = 0;
while ($copyHead !== null) {
$copyHead = $copyHead->next;
++$length;
}
$length -= $n;
$copyHead = $dummy;
while ($length > 0) {
$length--;
$copyHead = $copyHead->next;
}

$copyHead->next = $copyHead->next->next;

return $dummy->next;
}
}
14 changes: 14 additions & 0 deletions Tests/Helper/InputFiles/RemoveNthNodeFromEndOfListTest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"testCase1": {
"expectedResult":[2],
"input": [[1,2],2]
},
"testCase2": {
"expectedResult":[1,2,3,5],
"input": [[1,2,3,4,5],2]
},
"testCase3": {
"expectedResult":[],
"input": [[1],1]
}
}
29 changes: 29 additions & 0 deletions Tests/LinkedList/RemoveNthNodeFromEndOfListTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Hakam\LeetCodePhp\Tests\LinkedList;


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

/**
* @covers \Hakam\LeetCodePhp\LinkedList\RemoveNthNodeFromEndOfList
*/
class RemoveNthNodeFromEndOfListTest extends MainTest
{
use LinkedListHelperTrait;

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

0 comments on commit 9888f88

Please sign in to comment.