2626namespace doganoo \PHPAlgorithms \Common \Abstracts ;
2727
2828use doganoo \PHPAlgorithms \Common \Interfaces \IComparable ;
29+ use doganoo \PHPAlgorithms \Common \Interfaces \IUnaryNode ;
2930use doganoo \PHPAlgorithms \Common \Util \Comparator ;
3031use doganoo \PHPAlgorithms \Datastructure \Lists \Node ;
3132
@@ -492,6 +493,50 @@ public function compareTo($object): int {
492493 return -1 ;
493494 }
494495
496+ /**
497+ * also known as the Runner Technique
498+ *
499+ * @return bool
500+ */
501+ public function hasLoop (): bool {
502+ $ tortoise = $ this ->getHead ();
503+ $ hare = $ this ->getHead ();
504+
505+ while ($ tortoise !== null && $ hare ->getNext () !== null ) {
506+ $ hare = $ hare ->getNext ()->getNext ();
507+
508+ if (Comparator::equals ($ tortoise ->getValue (), $ hare ->getValue ())) {
509+ return true ;
510+ }
511+
512+ $ tortoise = $ tortoise ->getNext ();
513+ }
514+ return false ;
515+ }
516+
517+ /**
518+ * returns the middle node of the linked list
519+ *
520+ * @return IUnaryNode|null
521+ */
522+ public function getMiddleNode (): ?IUnaryNode {
523+ $ head = $ this ->getHead ();
524+
525+ if (null === $ head ) return null ;
526+
527+ $ p = $ head ;
528+ $ q = $ head ;
529+
530+ while (null !== $ p &&
531+ null !== $ q && //actually not really necessary since $p and $q point to the same object
532+ null !== $ q ->getNext ()
533+ ) {
534+ $ p = $ p ->getNext ();
535+ $ q = $ q ->getNext ()->getNext ();
536+ }
537+ return $ p ;
538+ }
539+
495540 /**
496541 * Specify data which should be serialized to JSON
497542 *
@@ -506,6 +551,7 @@ public function jsonSerialize() {
506551 ];
507552 }
508553
554+ //TODO implement
509555 //protected function removeDuplicates() {
510556 // $node = $this->head;
511557 // $previous = $this->head;
0 commit comments