Last active
August 29, 2015 14:18
-
-
Save cakper/63407c2a0f45a1b16b64 to your computer and use it in GitHub Desktop.
Palindrome
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 ListElement | |
{ | |
/** | |
* @var ListElement | |
*/ | |
private $next; | |
private $value; | |
/** | |
* ListElement constructor. | |
* @param $value | |
*/ | |
public function __construct($value, ListElement $next = null) | |
{ | |
$this->value = $value; | |
$this->next = $next; | |
} | |
/** | |
* @return ListElement | |
*/ | |
public function getNext() | |
{ | |
return $this->next; | |
} | |
/** | |
* @return int | |
*/ | |
public function getValue() | |
{ | |
return $this->value; | |
} | |
public function hasNext() | |
{ | |
return $this->next instanceof ListElement; | |
} | |
} | |
$head = new ListElement(3, new ListElement(4, new ListElement(2, new ListElement(4, new ListElement(3))))); | |
class Palindrome { | |
private $left; | |
public function isValid(ListElement $node){ | |
$this->left = $node; | |
return $this->recurse($node); | |
} | |
function recurse(ListElement $node) { | |
$previous = true; | |
if ($node->hasNext()) { | |
$previous = $this->recurse($node->getNext()); | |
} | |
if ($this->left->getValue() === $node->getValue() && $previous === true) { | |
$this->left = $this->left->getNext(); | |
return true; | |
} | |
return false; | |
} | |
} | |
$palindrome = new Palindrome(); | |
var_dump($palindrome->isValid($head)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment