Last active
July 9, 2021 07:30
-
-
Save f3ath/f34909128d5115f7a91e4b8d15391373 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Node | |
{ | |
/** | |
* @var string | |
*/ | |
private $value; | |
/** | |
* @var Node | |
*/ | |
private $next; | |
/** | |
* Node constructor. | |
* @param string $value | |
* @param Node $next | |
*/ | |
public function __construct(string $value, Node $next = null) | |
{ | |
$this->value = $value; | |
$this->setNext($next); | |
} | |
static public function fromString(string $s) | |
{ | |
$head = $last = null; | |
foreach (str_split($s) as $char) { | |
$node = new Node($char); | |
if ($last instanceof Node) { | |
$last->setNext($node); | |
$last = $node; | |
} else { | |
$head = $last = $node; | |
} | |
} | |
return $head; | |
} | |
static public function toString(Node $node = null) | |
{ | |
$s = ''; | |
while ($node instanceof Node) { | |
$s .= $node; | |
$node = $node->getNext(); | |
} | |
return $s; | |
} | |
static public function reverse(Node $node) | |
{ | |
$prev = null; | |
while ($node instanceof Node) { | |
$next = $node->getNext(); | |
$node->setNext($prev); | |
list($prev, $node) = [$node, $next]; | |
} | |
return $prev; | |
} | |
/** | |
* @return Node|null | |
*/ | |
public function getNext() | |
{ | |
return $this->next; | |
} | |
/** | |
* @param Node $next | |
*/ | |
public function setNext(Node $next = null) | |
{ | |
$this->next = $next; | |
} | |
public function __toString() | |
{ | |
return $this->value; | |
} | |
} | |
$test = [ | |
'', | |
'h', | |
'hello' | |
]; | |
foreach ($test as $s) { | |
$passed = strrev($s) === Node::toString(Node::reverse(Node::fromString($s))); | |
printf("'%s': %s\n", $s, $passed ? 'PASS' : 'FAIL'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment